Escape Single Quotes Within JavaScript

While I was trying to register a JavaScript code into an ASP.NET page I came across the need to ensure that passing a string to the JavaScript method would not cause an error ‘Unterminated string constant error’ upon rendering, this error could be caused if the string contains single quotes.

In this blog I will discuss this issue and I will propose some solutions to avoid this JavaScript error.In the following sample code I’m setting the “onclick” attribute from the code behind of the page, as you can see it will cause an error because of the appearance of the single quote

Html Code :

Html Code

Code behind:

Code behind

To solve this issue I propose the following solutions to escape single quotes in c# so that string will not cause any JavaScript issue.

First Solution


A simple solution in such cases is to use HTML codes for apostrophe, which is: '
So the string should be passed to the JavaScript funciton as:
string str = "This is an example – Jamil Hallal's blog";

Second Solution
 

This solution is based on the replacement of the single quote by "\\'" as per the following code: 

btnSubmit.Attributes.Add("onclick", string.Format("return ShowText('{0}')", str.Replace("'", \\'))); 

Third Solution


Use HttpUtility.JavaScriptEncode method if you are using .net framework 4


This way you will not face the 'Unterminated String constant' error anymore.
Published Tuesday, August 24, 2010 3:18 PM by jhallal
Filed under: ,

Comments

# re: Escape Single Quotes Within JavaScript

Wednesday, August 25, 2010 7:06 AM by Francis

Use

HttpUtility.JavaScriptStringEncode

Supported in: framework 4

msdn.microsoft.com/.../dd991914.aspx

# re: Escape Single Quotes Within JavaScript

Monday, April 18, 2011 6:20 AM by Ramakrishna

really helped, thank you very much

# re: Escape Single Quotes Within JavaScript

Wednesday, February 08, 2012 7:35 AM by somu

Its Very useful for me

# re: Escape Single Quotes Within JavaScript

Wednesday, February 08, 2012 7:36 AM by Somu

really its very useful, thank you so much

Leave a Comment

(required) 
(required) 
(optional)
(required)