Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape new lines with JS

Tags:

javascript

I have a string that looks something like this:

"Line 1\nLine 2"

When I call length on it, though, it's one character short:

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

Looking a little closer:

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

I find that the \n is being replaced by a single character, which looks like:

"
"

Is there a way to escape that new line into a \n?

like image 240
nullnullnull Avatar asked Sep 18 '14 19:09

nullnullnull


People also ask

How do you skip a new line in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

Why does \n not work in JavaScript?

Your question is not clear but if you mean why "\n" is not visible as text in js then it is because it is newline character i.e it can be used to get an similar effect as html <br> tag.

How do you escape a new line in HTML?

Escape the HTML, and then replace \n with <br> .


2 Answers

Whenever you get Javascript to interpret this string, the '\n' will be rendered as a newline (which is a single character, hence the length.)

To use the string as a literal backslash-n, try escaping the backslash with another one. Like so:

"Line 1\\nLine 2"

If you can't do this when the string is created, you can turn the one string into the other with this:

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

If you might have multiple occurrences of the newline, you can get them all at once by making the regex global, like this:

"Line 1\nLine 2\nLine 3".replace(/\n/g, "\\n");
like image 192
Jon Carter Avatar answered Sep 26 '22 02:09

Jon Carter


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

Keep in mind that the actual representation of a new line depends on the system and could be one or two characters long: \r\n, \n, or \r

like image 27
kapex Avatar answered Sep 22 '22 02:09

kapex