21-Apr-14 (Created: 21-Apr-14) | More in 'CS-JavaScript'

How to escape, encode special characters in javascript strings

http://www.kingsley-hughes.com/tech/script/javascript/esc.asp

Some times when server side needs to write out a string variable that initializes a javascript string it is important to know how to escape strings.

The usual html escape and unescape are either too heavy handed and require probably special handling.

A good approach may be just use the back slashes to skip the quote double or single quotes.

Apparently this doesn't work


<form name="mainform">
<input type="text" name="noteNameTextBox" size="57" value="\"hello\"">
</form>

But this does


<form name="mainform">
<input type="text" name="noteNameTextBox" size="57" value="">
</form>

<script>
document.mainform.noteNameTextBox.value="\"hello\"";
</script>