Javascript CR+LF 会断串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4715929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript CR+LF will break string?
提问by Riccardo
When storing '\n\r' inside a string constant it will make the Javascript engine throw an error like "unterminated string" and so on.
当将 '\n\r' 存储在字符串常量中时,它会使 Javascript 引擎抛出诸如“未终止的字符串”之类的错误。
How to solve this?
如何解决这个问题?
More info: basically I want to use Javascript to select text into a TEXTAREA HTML field and insert newlines. When trying to stuff those constants, I get an error.
更多信息:基本上我想使用 Javascript 将文本选择到 TEXTAREA HTML 字段中并插入换行符。尝试填充这些常量时,出现错误。
回答by Gumbo
String literalsmust not contain plain line break characters like CR and LF:
字符串字面量不得包含普通的换行符,如 CR 和 LF:
A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash
\. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as\nor\u000A.
“ LineTerminator”字符不能出现在字符串文字中,即使前面有反斜杠
\。使行终止符成为字符串文字的字符串值的一部分的正确方法是使用转义序列,例如\nor\u000A。
So having a line break like this is invalid:
所以有这样的换行符是无效的:
"foo
bar"
Instead you need to use an escape sequence like:
相反,您需要使用转义序列,例如:
"foo\nbar"
回答by Indra Ginanjar
use a backslash( \) before inserting new line.
在插入新行之前使用反斜杠( \)。
Example:
例子:
window.alert('foo\
bar');

