Riccardo
Riccardo

Reputation: 2216

Javascript CR+LF will break string?

When storing '\n\r' inside a string constant it will make the Javascript engine throw an error like "unterminated string" and so on.

How to solve this?

More info: basically I want to use Javascript to select text into a TEXTAREA HTML field and insert newlines. When trying to stuff those constants, I get an error.

Upvotes: 4

Views: 21938

Answers (1)

Gumbo
Gumbo

Reputation: 655489

String literals must not contain plain line break characters like CR and LF:

A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash \. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as \n or \u000A.

So having a line break like this is invalid:

"foo
bar"

Instead you need to use an escape sequence like:

"foo\nbar"

Upvotes: 9

Related Questions