What is the JavaScript string newline character?

JavascriptNewline

Javascript Problem Overview


Is \n the universal newline character sequence in JavaScript for all platforms? If not, how do I determine the character for the current environment?

I'm not asking about the HTML newline element (<BR/>). I'm asking about the newline character sequence used within JavaScript strings.

Javascript Solutions


Solution 1 - Javascript

I've just tested a few browsers using this silly bit of JavaScript:

function log_newline(msg, test_value) {
  if (!test_value) { 
    test_value = document.getElementById('test').value;
  }
  console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')
              + ' ' + (test_value.match(/\n/) ? 'LF' : ''));
}

log_newline('HTML source');
log_newline('JS string', "foo\nbar");
log_newline('JS template literal', `bar

baz`);

<textarea id="test" name="test">

</textarea>

IE8 and Opera 9 on Windows use \r\n. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n. They can all handle \n just fine when setting the value, though IE and Opera will convert that back to \r\n again internally. There's a SitePoint article with some more details called Line endings in Javascript.

Note also that this is independent of the actual line endings in the HTML file itself (both \n and \r\n give the same results).

When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)

I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:

lines = foo.value.split(/\r\n|\r|\n/g);

Solution 2 - Javascript

Yes, it is universal.

Although '\n' is the universal newline characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters ('\r').

Solution 3 - Javascript

Don't use "\n". Just try this:

var string = "this\
is a multi\
line\
string";

Just enter a backslash and keep on trucking! It works like a charm.

Solution 4 - Javascript

It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. For example, if you need to replace the newline then do the following:

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");

Solution 5 - Javascript

Yes, use \n, unless you are generating HTML code, in which case you want to use <br />.

Solution 6 - Javascript

In an email link function, I use "%0D%0A":

function sendMail() {
    var bodydata="Before "+ "%0D%0A";
        bodydata+="After"

    var MailMSG = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=subject"
             + "&body=" + bodydata;
    window.location.href = MailMSG;
}
HTML
<a href="#" onClick="sendMail()">Contact Us</a>

Solution 7 - Javascript

You can use `` quotes (which are below the Esc button) with ES6. So you can write something like this:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;

Solution 8 - Javascript

Get a line separator for the current browser:

function getLineSeparator() {
  var textarea = document.createElement("textarea");
  textarea.value = "\n"; 
  return textarea.value;
}

Solution 9 - Javascript

A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.

For example (to select a layer named 'Note' and add line feeds after all periods):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");

Solution 10 - Javascript

printAccountSummary: function()
    {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // Method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

Solution 11 - Javascript

I had the problem of expressing newline with \n or \r\n.
Magically the character \r which is used for carriage return worked for me like a newline.
So in some cases, it is useful to consider \r too.

Solution 12 - Javascript

I believe it is -- when you are working with JavaScript strings.

If you are generating HTML, though, you will have to use <br /> tags (not \n, as you're not dealing with JavaScript any more).

Solution 13 - Javascript

A practical observation... In my Node.js script I have the following function:

function writeToLogFile (message) {
    fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
        if (err) 
            throw err;
    });
}

First, I had only "\n", but I noticed that when I open the log file in Notepad, it shows all entries on the same line. Notepad++, on the other hand, shows the entries each on their own line. After changing the code to "\r\n", even Notepad shows every entry on its own line.

Solution 14 - Javascript

The \n is just fine for all cases I've encountered. If you are working with web, use \n and don't worry about it (unless you have had any newline-related issues).

Solution 15 - Javascript

You can use <br/> and the document.write/ and document.writeln one.

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
QuestionLandon KuhnView Question on Stackoverflow
Solution 1 - JavascriptmercatorView Answer on Stackoverflow
Solution 2 - JavascriptSinan TaifourView Answer on Stackoverflow
Solution 3 - JavascriptQasimView Answer on Stackoverflow
Solution 4 - JavascriptQuincyView Answer on Stackoverflow
Solution 5 - JavascriptFiner ReclinerView Answer on Stackoverflow
Solution 6 - JavascriptISCIView Answer on Stackoverflow
Solution 7 - JavascriptBogdan SuraiView Answer on Stackoverflow
Solution 8 - JavascriptVitalii FedorenkoView Answer on Stackoverflow
Solution 9 - JavascriptJayCrosslerView Answer on Stackoverflow
Solution 10 - JavascriptBarbs GView Answer on Stackoverflow
Solution 11 - JavascriptOraletView Answer on Stackoverflow
Solution 12 - JavascriptPascal MARTINView Answer on Stackoverflow
Solution 13 - Javascriptuser11717468View Answer on Stackoverflow
Solution 14 - JavascriptzzandyView Answer on Stackoverflow
Solution 15 - Javascriptomari PowellView Answer on Stackoverflow