TRomesh
TRomesh

Reputation: 4481

How to replace String with an image using JS

I'm trying to implement a chat system which consist of Smilies :) . i'm using react js and i want to check and replace the smiley symbols in the receiving string.

  return(<ListItem
           leftAvatar={<Avatar src="profile pic" />}
           primaryText="Name"
           secondaryText={
          <p>
         {item.message}
         </p>
          }
           secondaryTextLines={2}
          />
               );

the string i want to check is given by {item.message}. ive tried to replace the string with {item.message}.replace(/:)/g,'<img src="../../../img/smileys/smile53893.gif"/>');

but it doesn't work!

Upvotes: 0

Views: 2307

Answers (1)

Jarno Lonardi
Jarno Lonardi

Reputation: 376

What you are doing there is that you are inserting the image tag as an string into the DOM. You need to create real react elements, and replace the :) with the <img/> elements.

Here is a simplified version your code. Made also a demo about this for you.

var texts = item.message.split(/:\)/g);
var content = [];
for(var i = 0; i < texts.length - 1; i++) {
  content.push(texts[i]);
  content.push(<img src='https://upload.wikimedia.org/wikipedia/commons/e/e2/Bye.gif'/>);
}
return <div>{content}</div>;

Upvotes: 3

Related Questions