RegisterStartupScript Alert Error when carriage return is in the string

979 Views Asked by At

I have RegisterStartupScript in the code-behind class to alert error message -- it works fine except when the error has line feeds or carriage returns (I think). Here is the snippet:

The commented code works fine!

catch (Exception ex)
        {
           //Page.ClientScript.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Failure", "alert('ERROR: '), true);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", "alert('" + ex.Message.Replace("'", "\\'") + "');", true);
        }
1

There are 1 best solutions below

2
On

Line terminators are not allowed in js strings. Eliminate the line terminators (carriage returns, new line symbols etc.) using regular expressions:

var errorMsg = Regex.Replace(ex.Message, 
    @"[\u000A|\u000D|\u2029\u2028|\u000D\u000A]", " ");

Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", 
    String.Format("alert('{0}');", errorMsg), true);