开发者

Is there anyway to avoid an unterminated string literal error if I'm creating a string from an unknown source

I need to create a string in javascript fr开发者_如何学Pythonom 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....

// 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 %>')


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜