user2879704
user2879704

Reputation:

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

Upvotes: 4

Views: 6546

Answers (4)

Numant Santz
Numant Santz

Reputation: 180

This one works pretty well .replace(/\\r\\n?|\\n/g, '\n');

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

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, "")

Upvotes: 6

user663031
user663031

Reputation:

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.

Upvotes: 6

anubhava
anubhava

Reputation: 785146

You should use:

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

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

Upvotes: 3

Related Questions