replace newline string literal – ‘n’ in javascript

Tags: ,



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

Answer

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('an') 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.



Source: stackoverflow