How to 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 post, I will discuss the issue related to escaping single or double quotes in JavaScript strings (JavaScript Escape Quotes) and I will propose some workarounds to avoid the error caused by this issue. 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 :

How to Escape Single Quotes Within JavaScript, javascript escape quotes, js escape quotes, javascript escape quote, javascript escape single quote, javascript single quote in string, how to escape a single quote, c# escape apostrophe, escape quotes in javascript, javascript escape quotes in string, js escape quote, escape single quote c#, escape single quote html, javascript quote escape, js string escape quotes, escape apostrophe javascript, escape apostrophe in javascript, escape single quote c#, asp escape, html escape single quote, escape javascript, apostrophe html escape, escape quotes

Code behind:

How to Escape Single Quotes Within JavaScript, javascript escape quotes, js escape quotes, javascript escape quote, javascript escape single quote, javascript single quote in string, how to escape a single quote, c# escape apostrophe, escape quotes in javascript, javascript escape quotes in string, js escape quote, escape single quote c#, escape single quote html, javascript quote escape, js string escape quotes, escape apostrophe javascript, escape apostrophe in javascript, escape single quote c#, asp escape, html escape single quote, escape javascript, apostrophe html escape, escape quotes

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


JavaScript Escape Quotes - 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 function as: 
string str = "This is an example – Jamil Hallal's blog";

JavaScript Escape Quotes - 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("'"\\'))); 

JavaScript Escape Quotes - 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.

You can also check the following article: "JavaScript Escape Quotes"

Post a Comment

Previous Post Next Post