Ad

JavaScript / JQuery Escape Special Chars

- 1 answer

I need to escape a String with special characters and i dont know how to do that.

The String var value is set by an Input field, so the user can write any special character as he wants, even the ones that i dont know and i could break the syntax...so instead of escape char by char, i want to know what's the better method to accomplish this.

This is my example code:

string = '-|{}?" Hello \$#^*&@)(~';

newHTML= '<span class="color-red"><b>'+string+'</b></span>';

$('#my-div').append(newHTML);

But i get a syntax error.I want to escape all special characters... as you can see this code detector also is not working when i use ' in the string

Ad

Answer

Or easy jQuery trick:

string = $("<div></div>").text(string).html();

text() encodes the string inside the temporary div and html() fetches the encoded string :)

Ad
source: stackoverflow.com
Ad