JavaScript / jQuery escape special chars -


i need escape string special characters , dont know how that.

the string var value set input field, user can write special character wants, ones dont know , break syntax...so instead of escape char char, want know what's better method accomplish this.

this example code:

string = '-|{}?" hello \$#^*&@)(~';  newhtml= '<span class="color-red"><b>'+string+'</b></span>';  $('#my-div').append(newhtml); 

but syntax error.i want escape special characters... can see code detector not working when use ' in string

or easy jquery trick:

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

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


Comments