I need to create a string in javascript from some text that the user provides. When I try to run this line:
var str = new String('<%= @note.text %>')
I get the unterminated string literal error. Given that I have no control over what is inputed, and I can’t assign the string to start to do any character replacement, how do I fix this problem? Thanks for reading.
There’s nothing you can do client-side, you need to sanitize the string on the server. Given that you’re putting the literal into the String constructor via <%= %>, I assume you’re using some variety of ASP.Net.
I’m sure there’s a more elegant way to do this, but this should work as a first pass at encoding a string for use in JavaScript. This makes no attempt at addressing the relative merits of passing arbitrary strings to JavaScript in the first place. (For most cases, there should very likely be some server-side checks for malicious strings.)
Assuming note is a text input field, something like this might work….
In the OnLoad(), add
And finally, in your .aspx