views:

29

answers:

2

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.

+1  A: 

You can't throw arbitrary text into JS and be able to recover from errors.

You must sanitize the data before putting it into the document. I don't know why you think you can't do that, but you need to remove whatever barriers are preventing it.

David Dorward
+1  A: 

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....

// New Property in your code behind
public string outputText {get; private set;}

In the OnLoad(), add

// Encode the string
string tempText = Note.Text
outputText = String.empty;
foreach( char character in tempText)
{
  // Prefix quotation mark with a backslash,
  if(char == "\"")
    outputText += "\\\"";
  // Prefix apostrophe with a backslash,
  else if(char == "'")
    outputText += "\\'";
  // convert newline to a literal.
  else if(char == "\n")
    outputText += "\\n";
  else
    outputText += character;
}

And finally, in your .aspx

var str = new String('<%= outputText %>')
ThatBlairGuy