Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript string with new line - but not using \n

People also ask

How do you pass a new line in a string in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

Does \n work in JavaScript?

"\n" does work. If you do a document.

Is it n or \n for new line?

Operating systems have special characters denoting the start of a new line. For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

Does \n work in a string?

in a string prevents actually making a new line and instead of Type (new line) for a new line it is Type \n for a new line .


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

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

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

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


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