Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  172] [ 5]  / answers: 1 / hits: 71837  / 10 Years ago, thu, september 18, 2014, 12:00:00

I have a string that looks something like this:



Line 1nLine 2


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



Line 1nLine 2.length // 13


Looking a little closer:



Line 1nLine 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?


More From » javascript

 Answers
25

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 1nLine 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 1nLine 2nLine 3.replace(/n/g, \n);

[#69406] Tuesday, September 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;