Search This Blog

Thursday, March 19, 2015

Show apostrophe in Javascript


In many scenarios, we need to call some Javascript method in our applications. Most common of which can be javascript:alert('message'). We ususlly pass out string in javascript alert, but if the string contains ( ' ) character, the method fails and throw an exception as:

alert('This ' will terminate the string');





One way to resolve this is to replace "'" with ' like:

alert('string works well with ' used here');

However you need to ensure that you are not using this on Older versions of Internet Explorer since ' is not supported in earlier versions of HTML. For behaving correctly in older versions also, you can use: '

alert('This works in all the browsers for the constant '');

If you are working on .Net Framework 4.0, then you can also make use of the folllowing property to create a javascript supported script as:

HTTPUtility.JavascriptEncode("the constant ' is supported here")

No comments:

Post a Comment