JavaScript string with new line - but not using \n

JavascriptString

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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!"

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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).

Solution 6 - Javascript

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

Solution 7 - Javascript

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...

Solution 8 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1082754View Question on Stackoverflow
Solution 1 - JavascriptRandy the DevView Answer on Stackoverflow
Solution 2 - JavascriptDavid RefouaView Answer on Stackoverflow
Solution 3 - JavascriptcfedermannView Answer on Stackoverflow
Solution 4 - JavascriptSimon EdströmView Answer on Stackoverflow
Solution 5 - JavascriptEvertView Answer on Stackoverflow
Solution 6 - JavascriptJ.T. HoutenbosView Answer on Stackoverflow
Solution 7 - JavascriptYaron U.View Answer on Stackoverflow
Solution 8 - JavascriptDikshit KathuriaView Answer on Stackoverflow