Surendra Sharma

Surendra Sharma

Search This Blog

Monday, August 26, 2013

Unterminated string constant


I was working today to display message in javascript alert() function.

I was passing message from C# code to javascript function as

protected void btnShow_Click(object sender, EventArgs e)
{
    StringBuilder strMsg = new StringBuilder();

    strMsg.AppendLine("Product ID: 101");
    strMsg.AppendLine("This product is not available.");
    strMsg.AppendLine("Please select another product.");

    string strMessage = strMsg.ToString();
   
    ScriptManager.RegisterClientScriptBlock(this, typeof(Button), "ShowMessage", "AlertInfo('" + strMessage + "');", true);
}

My Javascript looks like this

<script type="text/javascript">

    function AlertInfo(msg) {
        alert(msg);
    }
   
</script>

When I run the code and click on my Show button, browser welcomes me by displaying javascript error as “Unterminated string constant”.

When I investigated it, I come to know that I was using AppendLine method which introduced \r\n newline characters in string message. So my final message looks something like this

Product ID: 101\r\nThis product is not available.\r\nPlease select another product.\r\n

Then I replacess all occureneces of \r\n by space as below

string strMessage = strMsg.ToString();
strMessage = strMessage.Replace("\r\n", " ");
ScriptManager.RegisterClientScriptBlock(this, typeof(Button), "ShowMessage", "AlertInfo('" + strMessage + "');", true);

By replacing \r\n message with space solve my problem

strMessage = strMessage.Replace("\r\n", " ");

So never pass \r\n to javascript variables, parameters, functions.



Please leave your comments or share this tip if it’s useful for you.

1 comment:

  1. Why not change your stringbuilder to use Append() instead of AppendLine which then no longer create the newline info?

    ReplyDelete