简体   繁体   中英

replace newline string literal - '\n' in javascript

I have string literal, \\n in a variable. 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 . I expect no output from 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

Don't do like \\\\[rn] . ie, Don't separate backslash and r , n . 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

No you don't. You have \\(newline) , which is a quite different thing.

var value = "\\\n"

value is a string of length two. 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 . But your input contains a newline in the second position. A newline matches neither r nor n . Hence nothing is replaced, and value retains its original 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. console.log('\\n') prints an empty line as expected. However, console.log('a\\n') prints only the a , with no apparent newline. In other words, Chrome devtools (as well as FF) appears to suppress the final trailing newline in certain situations.

You should use:

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

This will replace \\r or \\n which is followed by a literal \\ in your input.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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