alert("...");
var values = "value1
valu2part1 value2part2
value3
valu4";
alert(values);
I am assigning:
var values = "<%=Model.Values%>";
These values are stored in a database. The values are entered through a textarea
and in the database each line is seperated by \t\r.
When I take this to a JavaScript variable using:
var values = "<%=Model.Values%>";
I am getting some thing like:
var values = "value1
valu2part1 value2part2
value3
valu4";
But this is anerror. What can I do?
2 Answers 2
var values = "<%=Model.Values%>";
This is unsafe. Not only will it fail when there are newlines in the string (as JavaScript string literals cannot span multiple lines), it's also possible for a " in the value to end the string prematurely. If the value contains user-submitted data, that's a script-injection security hole (XSS).
To create JS literal syntax use a JSON serialiser. For example with JavaScriptSerializer:
var values= <%= new JavaScriptSerializer().Serialize(Model.Values) %>;
or eg Json.NET if you're on older .NET versions.
Comments
You can replace your new lines with escape sequences (\n) before outputting your string to the JS.