Escape new lines with JS

I have a line that looks something like this:

"Line 1\nLine 2" 

When I find the length on it, this one character is short:

 "Line 1\nLine 2".length // 13 

The look is a little closer:

 "Line 1\nLine 2".charAt(6) 

I find that \n is replaced with a single character that looks like this:

 " " 

Is there any way to avoid this new line in \n ?

+8
javascript
source share
3 answers

Whenever you get Javascript to interpret this line, "\ n" will be displayed as a new line (this is one character, which means length).

To use a string as a backslash literal-n, try backsliding with a different one. For example:

 "Line 1\\nLine 2" 

If you cannot do this when a line is created, you can include one line in another:

 "Line 1\nLine 2".replace(/\n/, "\\n"); 

If you can have multiple occurrences of a new line, you can get them all at once by making a global regular expression, for example:

 "Line 1\nLine 2\nLine 3".replace(/\n/g, "\\n"); 
+6
source share

\n is a newline character. You can use "Line 1\\nLine 2" to avoid it.

Keep in mind that the actual representation of a newline is system dependent and may contain one or two characters: \r\n , \n or \r

+5
source share

In JavaScript, the backslash in a string literal is the start of an escape code , such as the backslash n for a new line. But what if you need a real backslash in the resulting string? One of the escape codes is a backslash with a backslash, for a real backslash.

0
source share

All Articles