Question

I try to make a simple chatroom, But how to I strip <script>'s tag from chat msg ?

HTML :

<div></div>
<textarea>Hello , <script>alert('world');</script>
This is a new line !
</textarea>
<button>Send</button>

jQuery :

$('button').click(function(){
    var msg = $('textarea').val().replace(/\r\n|\r|\n/g,"<br />")
    $('div').append(msg);
});

When user click 'send', I want the result to be

Hello , alert('world');

This is a new line !

without <script></script> tags but with <br> tag instead of newline.

Playground : http://jsfiddle.net/rGNEe/

Was it helpful?

Solution

Like this.

Live Demo

$('button').click(function(){
    var msg = $('textarea').val().replace(/(<([^>]+)>)/ig,"").replace(/\r\n|\r|\n/g,"<br />")
    $('#res').append(msg);
});

OTHER TIPS

Try

$('button').click(function(){
    var msg = $('textarea').val().replace(/\r\n|\r|\n/g,"<br />").replace(/</, '&lt;').replace(/>/, '&gt;')
    $('div').append(msg);
});

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top