1

I've been working in a Chat Box, I use Node.js + socket.io for client-server communication so I can't execute PHP code(I've read that is possible but It's not recommended and difficult to achieve). Everything works fine except when users send messages with HTML or Scripts tags.

I've tried to remove those tags with a function that I found in here. It works fine, but only for HTML tags, then I thought: Well, I can remove Script tags first using regular expressions. Something like this

.replace(/<script.*>.*<\/script>/ims, " ")

and then remove the HTML tags, but I'm not sure if this method is hacks proof, and that's a lot of processes for each message sent.

Is there any form of appending text$("#div").append(message); without rendering HTML/JavaScript code ? --- Print the text just the way it is, like in twitch.tv, in there, if you send a message with HTML/JS/PHP code, the message is printed just like the way you type it.

or, is there any other way to remove tags ?

Thanks for your time.

2
  • 2
    You can call .text() function. Mar 26, 2013 at 20:30
  • .append() appends to the div. .text() will replace the entire div. Not a good idea IMO Jun 11, 2019 at 14:02

1 Answer 1

1

Just append a div with the message set as text.

$("#div").append( $("<div>").text(message) );
2
  • Nice idea, thanks, it worked. I think this time I went to far away from the easiest solution
    – Mollo
    Mar 26, 2013 at 20:49
  • I just realized that, it's adding me a break line at the end for each append I do in that way. How could I fix it ? Thank you.
    – Mollo
    Mar 27, 2013 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.