I’m outputting client side function calls from code behind via
Page.ClientScript.RegisterStartupScript( this.GetType(), "supportItems", scriptCalls, true );
scriptCalls contains call(s) to a client side function that has several string arguments taken from database and that then displays the parameters in HTML textareas, so line breaks need to ultimately be preserved. If the DB value includes a linebreak then the linebreak gets included in the outputted client script which of course then causes a client script error.
I have tried passing the DB values through a cleaning function to replace line breaks ala:
private string CleanJavaScriptString( string stringToClean )
{
string cleanString = stringToClean.Replace( "'", "\'" );
cleanString = cleanString.Replace( Environment.NewLine, "\n" );
return cleanString;
}
But this still outputs the actual line break in the code. How can I achieve this?
If you have access to it (.NET 3.5 onwards), the best bet it to use
JavaScriptSerializer…This is taken from the this question/answer.
The advantage of the JavaScriptSerializer is that it will deal with quotes, newlines – and all the characters you might not have thought about, which would affect JavaScript.
EDIT
And here is a C# equivalent to what you’re asking for…