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 :

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 SolutionA 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 4This way you will not face the 'Unterminated String constant' error anymore.