JavaScript string with new line - but not using \n
Asked Answered
L

9

82

I have a string that has new lines in. I am wanting to convert these to HTML <br>s, but I'm having a hard time detecting them.

Imagine a JavaScript string set like this:

var foo = "Bob
is
cool";

They are the kind of new lines that I need to detect. They aren't using the \n special character - they are just plain format.

Lollard answered 14/4, 2012 at 14:40 Comment(6)
That is \n (unless it's possibly also \r)Biology
I think he meant that they're not expressed with the \n escape sequence, but rather that the character is literally there in the source code.Quadri
@Pointy: but the result would still be the same, provided this wasn't a syntax error.Emprise
"Plain format" newlines are simply the visible result of a \n special character. \n is just an alias of it.Ingeminate
@Emprise yes I agree of course; I'm thinking syntax error too.Quadri
As of 2016 there is a way to do this: https://mcmap.net/q/241920/-javascript-string-with-new-line-but-not-using-nStarrstarred
I
91

The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

When you have a string which looks like this:

//Note lack of terminating double quote
var foo = "Bob 

Your code will have a syntax error at that point and cease to run.

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";
Ingeminate answered 14/4, 2012 at 14:59 Comment(1)
Aug 2016 Update: There is NOW a way to do this: https://mcmap.net/q/241920/-javascript-string-with-new-line-but-not-using-nStarrstarred
S
91

UPDATE: I just came across a wonderful syntax design in JavaScript-ES6 called Template literals. What you want to do can be literally be done using ` (backtick or grave accent character).

var foo = `Bob
is
cool`;

In which case, foo === "Bob\nis\ncool" is true.

Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me.

Just be sure that the targeting browser supports ES6-specified Javascript implementation.

 


P.S. This syntax also supports a pretty cool feature that is present in PHP, .NET, and some other scripting languages; namely "Tagged template literals" with which you can build a parameterized string like this:

var a = 'Hello', b = 'World';
console.log(`The computer says ${ a.toUpperCase() }, ${b}!`);
// results in "The computer says HELLO, World!"
Starrstarred answered 30/10, 2016 at 23:20 Comment(7)
I am trying to use `` in Google Apps script IDE and it says "Illegal character.". How to handle?Nympha
@Nympha It seems that Google Apps doesn't support ES6 syntax (the version of javascript that allows this),Starrstarred
@Nympha so I suggest learning and using Babel in order to "transpile" ES6 to older versions of compatible javascript for Google Apps scripts. You can also ask a new question titled "How to use ES6 in Google Apps script IDE", maybe someone has a solution for it.Starrstarred
Can I give you 10 upvotes for the backtick answer? It really works like magic! :)Doerr
"Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me." - The developers of Javascript in 1995 were not the same as the ones in 2015. And changing old-style strings would break old code. Pretty clear reasoning.Strake
@JimmieTyrrell In hindsight, you're clearly correct. I guess I'm more infuriated by the fact that they decided against changing the older syntax to avoid breaking old code as you put it, despite that " ... <newline> ... " and ' ... <newline> ... ' were still invalid syntax, so I wouldn't see the point of not changing them to allow the same newline syntax.Starrstarred
best answer broInner
G
9

Check for \n or \r or \r\n.

There are several representations of newlines, see http://en.wikipedia.org/wiki/Newline#Representations

Gretchen answered 14/4, 2012 at 14:43 Comment(1)
I'm doing that. I've checked for all three: console.log(story.message.split(/\n/g)); console.log(story.message.split(/\r/g)); console.log(story.message.split(/\r\n/g)); They all return the same. No split.Lollard
L
3

I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

Ledesma answered 14/4, 2012 at 14:44 Comment(0)
E
3

I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

Emprise answered 14/4, 2012 at 14:44 Comment(1)
Thanks. In that case, why won't this work? console.log(story.message.split(/\n/g)); console.log(story.message.split(/\r/g)); console.log(story.message.split(/\r\n/g)); They all return the same. No splitLollard
I
3

you can use the following function:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  } 

like so:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

this imitates the nl2br function in php...

Indent answered 14/4, 2012 at 14:44 Comment(0)
C
3

This is a small adition to @Andrew Dunn's post above

Combining the 2 is possible to generate readable JS and matching output

 var foo = "Bob\n\
    is\n\
    cool.\n\";
Conglomerate answered 23/6, 2016 at 9:6 Comment(0)
C
0

The query string that I used to to escape the new line character in JS : LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;

This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.

PS: This example is my query to upload CSV data into mysql DB.

Cockroach answered 3/5, 2019 at 9:8 Comment(0)
L
0

I had a unique spin on this problem. I'm doing a script in an HTML block in WPForms (Wordpress). The thing kept eating the \ out of my \n overnight, and i'm trying to output a csv. So i used this:

return csvarray.join(`
`);

using the backtick makes sure the line break in my code is encoded into the string without using the \n, thus circumventing the filter that was breaking my escape characters :)

Lyndell answered 25/4 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.