Escape apostrophe in javascript and dynamic built scripts

The apostrophe in javascript is its string delimiter. To render the apostrophe on the response without errors it must be escaped using backslash \.

alert('John\'s name') will produce message box with text: John's name.

Using usually the scripts are built dynamically on server side before rendering the page. Remember that the backslash is also escape character in C# and you have to put two backslashes to build the javascript correctly:

Response.Write("alert('John\\'s name');");

No comments:

Post a Comment