Like this.
$('button').click(function(){
var msg = $('textarea').val().replace(/(<([^>]+)>)/ig,"").replace(/\r\n|\r|\n/g,"<br />")
$('#res').append(msg);
});
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/
Solution
Like this.
$('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(/</, '<').replace(/>/, '>')
$('div').append(msg);
});
Demo: Fiddle