Javascript 使用 JS 转义新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25921319/
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
Escape new lines with JS
提问by nullnullnull
I have a string that looks something like this:
我有一个看起来像这样的字符串:
"Line 1\nLine 2"
When I call length on it, though, it's one character short:
但是,当我调用 length 时,它会短一个字符:
"Line 1\nLine 2".length // 13
Looking a little closer:
再近一点看:
"Line 1\nLine 2".charAt(6)
I find that the \nis being replaced by a single character, which looks like:
我发现\n正在被单个字符替换,如下所示:
"
"
Is there a way to escape that new line into a \n?
有没有办法将那条新线转义到\n?
采纳答案by Jon Carter
Whenever you get Javascript to interpret this string, the '\n' will be rendered as a newline (which is a single character, hence the length.)
每当您使用 Javascript 来解释此字符串时,'\n' 将呈现为换行符(它是单个字符,因此是长度。)
To use the string as a literal backslash-n, try escaping the backslash with another one. Like so:
要将字符串用作文字反斜杠-n,请尝试用另一个反斜杠转义。像这样:
"Line 1\nLine 2"
If you can't do this when the string is created, you can turn the one string into the other with this:
如果在创建字符串时无法执行此操作,则可以使用以下命令将一个字符串转换为另一个:
"Line 1\nLine 2".replace(/\n/, "\n");
If you might have multiple occurrences of the newline, you can get them all at once by making the regex global, like this:
如果您可能多次出现换行符,您可以通过将正则表达式设为全局来一次性获取它们,如下所示:
"Line 1\nLine 2\nLine 3".replace(/\n/g, "\n");
回答by kapex
\nis the newline character. You can use "Line 1\\nLine 2"to escape it.
\n是换行符。你可以用"Line 1\\nLine 2"它来逃避它。
Keep in mind that the actual representation of a new line depends on the system and could be one or two characters long: \r\n, \n, or \r
请记住,新线的实际表现取决于系统,可能是一个或两个字符长:\r\n,\n或\r
回答by rakslice
In JavaScript, a backslash in a string literal is the start of an escape code, for instance backslash n for a newline. But what if you want an actual backslash in the resulting string? One of the escape codes is backslash backslash, for an actual backslash.
在 JavaScript 中,字符串文字中的反斜杠是转义码的开始,例如反斜杠 n 表示换行符。但是,如果您想要在结果字符串中使用实际的反斜杠怎么办?转义码之一是反斜杠反斜杠,表示实际的反斜杠。

