简体   繁体   English

替换换行字符串文字 - '\\n' 在 javascript 中

[英]replace newline string literal - '\n' in javascript

I have string literal, \\n in a variable.我有字符串文字, \\n在一个变量中。 I am trying to replace it with empty string.我试图用空字符串替换它。 But it doesn't work.但它不起作用。

var value = "\\\n"
value = value.replace(/(?:\\[rn])+/g, "")
console.log(value)

value evaluates to the string literal - \\n . value 计算为字符串文字 - \\n I expect no output from console.log .我希望console.log没有输出。 But it prints但它打印

\

Empty line followed by a backward slash (for some reason, stack overflow has trimmed the empty line in above output).空行后跟反斜杠(出于某种原因,堆栈溢出已修剪了上面输出中的空行)。

Note, this question is not related to replacing newline character - \\n请注意,此问题与替换换行符无关 - \\n

Don't do like \\\\[rn] .不要像\\\\[rn]那样做。 ie, Don't separate backslash and r , n .即,不要将反斜杠和rn分开。 This would change its meaning.这将改变其含义。

value.replace(/[\r\n]+/g, "")

If you also want to replace the backslash character which exists before carriage return or newline character then add \\\\ before the character class.如果您还想替换回车符或换行符之前存在的反斜杠字符,则在字符类之前添加\\\\

value.replace(/\\[\r\n]+/g, "")

I have string literal, \\n in a variable我有字符串文字, \\n在一个变量中

No you don't.不,你没有。 You have \\(newline) , which is a quite different thing.你有\\(newline) ,这是完全不同的事情。

var value = "\\\n"

value is a string of length two. value是一个长度为 2 的字符串。 The first character is a backslash.第一个字符是反斜杠。 The second character is a newline.第二个字符是换行符。

value = value.replace(/(?:\\[rn])+/g, "")

Your regexp attempts to replace a literal backslash followed by either the letter r or the letter n .您的正则表达式尝试替换后跟字母r或字母n的文字反斜杠。 But your input contains a newline in the second position.但是您的输入在第二个位置包含换行符。 A newline matches neither r nor n .换行符既不匹配r也不匹配n Hence nothing is replaced, and value retains its original value.因此没有任何东西被替换, value保持其原始价值。

To see this more clearly:为了更清楚地看到这一点:

> for (i = 0; i < value.length; i++) console.log(value.charCodeAt(i));
< 92
< 10  // this is a newline

You may have been confused by some non-intuitive behavior in the Chrome devtools console.您可能对 Chrome devtools 控制台中的一些非直观行为感到困惑。 console.log('\\n') prints an empty line as expected. console.log('\\n')按预期打印一个空行。 However, console.log('a\\n') prints only the a , with no apparent newline.但是, console.log('a\\n')只打印a ,没有明显的换行符。 In other words, Chrome devtools (as well as FF) appears to suppress the final trailing newline in certain situations.换句话说,Chrome devtools(以及 FF)在某些情况下似乎会抑制最后的尾随换行符。

You should use:你应该使用:

value = value.replace(/\\[\r\n]+/g, "");
// ""

This will replace \\r or \\n which is followed by a literal \\ in your input.这将替换\\r\\n后跟输入中的文字\\

这个效果很好.replace(/\\\\r\\\\n?|\\\\n/g, '\\n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM