Safe JavaScript String

It is common that many a times we will be ejecting JavaScript string from server side code for showing exception message, alert message, warning messages, any other messages. While doing so, if the message contains carriage return, line feed will cause JavaScript errors.

In order to avoid such errors we need to handle such special characters. To make that job simple, Microsoft AJAX library has got a JavaScriptSerializer in System.Web.Script.Serialization. Using that we can get safe JavaScript strings. Actually this class is not meant for this purpose, its main use is to convert any object into JSON object and back. JSON internally a string type of key and value, they have to handle such script breaking due to special characters.

   public string GetSafeJSString(string input)


    if ((input != null)) {

        return new JavaScriptSerializer().Serialize(input);


    else {

        return "";



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s