1

I have this line of code:

var newmsg = $('<div class="message msg_owner">' + 
"<span class='msg_date'>"+dateFormat(timesp)+
"</span><span class='msg_seperator'> | </span><span class='msg_name'>" +
pseudo + '</span> : <span class="msg"></span></div>');
newmsg.find(".msg").text(replaceEmoticons(msg));
$("#chatEntries").append(newmsg);

Which basically creates divs or classes, then finds class named .msg and inserts text into it. replaceEmoticons(msg); is a function that finds all character sets of smileys (:D, :), :(, etc...) and converts them into something like:

<img src='http://example.com/public/images/smileys/laugh.png' id='chat_smls'/>

So I end up having message like:

Original:

Hello how are you? :)

It becomes:

Hello how are you? <img src='http://example.com/public/images/smileys/happy.png' id='chat_smls'/>

However, after the line:

newmsg.find(".msg").text(replaceEmoticons(msg));

That returns the code as text and in chat window it literally appears as the html img tag with all its attributes. From my understanding this is because of .text? If so, how can I fix it to strip all JS and other tags that may cause problems but leave that img?

arleitiss
  • 1,304
  • 1
  • 14
  • 38

2 Answers2

3

Instead of using .text, you should use .html

newmsg.find(".msg").html(replaceEmoticons(msg));

Notice that your script could be vulnerable to to cross-site-scripting, so you want to replace all html special characters with entities before replacing smileys with imgs, in your replaceEmoticons

Community
  • 1
  • 1
  • using .html lets JS functions through if user types them. I just entered: and it threw me popup (It executes for the Person Who Wrote it but not for others since I have all the other parts secured against that) – arleitiss Mar 01 '15 at 19:16
2

Yes, that's what text method does. If I have understood the question correctly you can use text and html methods:

newmsg.find(".msg").text(msg).html(function(_, currentContent) {
    return replaceEmoticons(currentContent);
});

text method converts all applicable characters to HTML entities and html method sets the innerHTML property by using the returned value of the replaceEmoticons function.

Ram
  • 143,282
  • 16
  • 168
  • 197