nullnullnull
nullnullnull

Reputation: 8189

Escape new lines with JS

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?

Upvotes: 18

Views: 88757

Answers (4)

Jimmi Jønsson
Jimmi Jønsson

Reputation: 169

If anyone else like me, ended up here to unescape new line characters rather than escaping them, this was my solution.

'Line1\\n\\nLine2'.replace(/\\n/g, '\n')

And as utils function

const unescapeNewLine = (str) => str.replace(/\\n/g, '\n')

Upvotes: 0

rakslice
rakslice

Reputation: 8975

In JavaScript, a backslash in a string literal is the start of an escape code, for instance backslash n for a newline. But what if you want an actual backslash in the resulting string? One of the escape codes is backslash backslash, for an actual backslash.

Upvotes: 0

Jon Carter
Jon Carter

Reputation: 3406

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

Upvotes: 25

kapex
kapex

Reputation: 29949

\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

Upvotes: 6

Related Questions