502

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
  • 7
    I have a multiline input control where the user is expected to enter a newline separated list. I need to parse the list by first splitting the string on newlines. – Landon Kuhn Jul 20 '09 at 20:41
  • 8
    @landon9720: For my multiline input controls, I have a `getValue` function that takes the `value` and returns `value.replace(/\r\n/g,'\n')` - just to keep the output consistent across browsers/platforms. – Roy Tinker Mar 08 '12 at 17:16
  • 1
    Good question especially for those who are new to programming! Outside of HTML and in JavaScript it is good to know how to break to the next/new line. – Eric Bishard May 11 '15 at 19:57
  • Checkout https://www.npmjs.com/package/eol – ryanve Feb 18 '17 at 08:58
  • I have used this in my console and got 2 different results. var a = "Hello"; var b = "world"; When I am trying to show this like a + "\n" + b; it gives me the output as Hello\nworld but if I put it in the console like console.log(a+"\n"+b); it gives the output as Hello and world in 2 different lines. – Ajish Kumar Jun 29 '22 at 18:16

15 Answers15

396

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);
mercator
  • 28,290
  • 8
  • 63
  • 72
  • 14
    Worked for me, had to use global flag though: /\r\n|\r|\n/g – AdrianoFerrari Feb 11 '12 at 01:01
  • 20
    @Edson and wrong, since it will treat `\r\n` as two newlines instead of one. If you want short, `/\r?\n/g` will probably do (who still uses Mac OS 9 anyway?). – mercator Mar 27 '13 at 22:22
  • 1
    Given that the SitePoint article is from 2004, the information there may not be relevant to current JS implementations. – cbmanica Oct 01 '13 at 23:52
  • 1
    Match is supposedly much faster than split: http://jsperf.com/regex-split-vs-match – Wilt Mar 20 '14 at 13:03
  • Does it mean a string can have different lengths in different browsers/systems depending on using `CRLF` vs `CR` for line breaks? – Ilya Loskutov May 24 '23 at 21:33
94

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

Sinan Taifour
  • 10,521
  • 3
  • 33
  • 30
  • 64
    \n is the universal *line feed* character (LF). The exact newline byte sequence depends on the platform (\r\n, \n, or \r: http://en.wikipedia.org/wiki/Newline). And *that's* the question landon is asking. You're contradicting yourself when you first say it's the universal newline character, and then say it may be preceded by a CR. Which one is it? – mercator Jul 20 '09 at 20:23
  • 2
    \n is the newline(line feed) character, even if it is preceded by a carriage return. CR should never be used on its own, although most Windows apis and apps will parse it as a newline. LF works just as well in Windows too. CR is just an artifact from the time when computers were merely electronic typewriters. – GolezTrol Jul 18 '11 at 19:34
  • 4
    @GolezTrol There are valid reasons to use CR on its own. For instance, returning to the beginning of the line in a console window in order to overwrite the line, without moving to the next line. This is often used to write changing percent progress indicators in command line utilities. – Dan Bechard Nov 09 '15 at 15:55
  • 3
    @Dan Thanks for the feedback. Of course, I should never have said "never", because there are indeed applications for a CR on its own. But the question is about Javascript not about command line utilities. Of course there may be a script running in CLI mode (although I don't know if CR will work like you said then), and you may even use Javascript to generate a script which is run in the command line. Those are possible exceptions to the rule, but in the context of the question they seem not to apply. Nevertheless, thanks for mentioning it. – GolezTrol Nov 09 '15 at 16:16
  • ~preceded~ => **preceded or succeeded** – sergiol Sep 01 '23 at 09:32
76

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Qasim
  • 1,554
  • 1
  • 13
  • 22
  • 2
    ES6 also supports multiline values with the `tilde` character(otherwise called a backtick). – Qasim Jul 08 '16 at 09:10
  • 20
    @Qasim - FYI, I believe tilde and backtick are different characters, see [`~` Tilde](https://en.wikipedia.org/wiki/Tilde) vs [`\`` Backtick](https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming). – Chris Burgess Oct 23 '16 at 04:14
  • 1
    Ah - Yup, you're right. ES6 uses the backtick character for multiline strings – Qasim Oct 31 '16 at 11:59
  • 4
    Although legal, that is frowned upon in JS circles. It lacks readability. if you can, use ES6's backticks. If not, \n – gotofritz May 07 '17 at 00:14
  • Is `"this\"` really less readable than `"this\n"`. Fairly subjective if you ask me... I like saving a character (and keypress) anywhere I can. Developers are lazy :) – Qasim May 07 '17 at 08:08
  • 7
    When writing code this works. It looks like the OP is about parsing text from a textarea though. – jinglesthula May 30 '17 at 16:21
61

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>");
Quincy
  • 1,710
  • 14
  • 20
28

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Finer Recliner
  • 1,579
  • 1
  • 13
  • 21
16

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

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

    var MailMSG = "mailto:aaa@sss.com"
             + "?cc=07@sss.com"
             + "&subject=subject"
             + "&body=" + bodydata;
    window.location.href = MailMSG;
}

HTML

<a href="#" onClick="sendMail()">Contact Us</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ISCI
  • 346
  • 3
  • 7
14

With ES6, you can use backtick quotes (``), which is below the Esc button on any US layout keyboard with size 75% or greater. So you can write something like this:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;
uzluisf
  • 2,586
  • 1
  • 9
  • 27
Bogdan Surai
  • 1,197
  • 14
  • 16
8

Get a line separator for the current browser:

function getLineSeparator() {
  var textarea = document.createElement("textarea");
  textarea.value = "\n"; 
  return textarea.value;
}
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
  • 3
    How about `return textarea.value;`? – XP1 Jan 31 '12 at 21:55
  • Will using `JSON.stringify` on the result change the character? If I try to view the result in an `alert()` call it doesn't show me the character unless I stringify it first (not that the char needs to be human readable to be effective, of course) –  Oct 20 '14 at 20:06
4

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");
JayCrossler
  • 2,079
  • 2
  • 22
  • 22
3
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%.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Barbs G
  • 41
  • 1
2

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.

Oralet
  • 349
  • 1
  • 2
  • 11
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-3

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zzandy
  • 2,263
  • 1
  • 23
  • 43
-14

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131