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.
Html Code :
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.
JavaScript Escape Quotes - First Solution
So the string should be passed to the JavaScript
function as:
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"