Skip to content
Advertisement

Line endings (also known as Newlines) in JS strings

It is well known, that Unix-like system uses LF characters for newlines, whereas Windows uses CR+LF.

However, when I test this code from local HTML file on my Windows PC, it seems that JS treat all newlines as separated with LF. Is it correct assumption?

var string = `
    foo




    bar
`;

// There should be only one blank line between foo and bar.

// n - Works
// string = string.replace(/^(s*n){2,}/gm, 'n');

// rn - Doesn't work
string = string.replace(/^(s*rn){2,}/gm, 'rn');

alert(string);

// That is, it seems that JS treat all newlines as separated with 
// `LF` instead of `CR+LF`?

Advertisement

Answer

I think I found an explanation.

You are using an ES6 Template Literal to construct your multi-line string.

According to the ECMAScript specs a

.. template literal component is interpreted as a sequence of Unicode code points. The Template Value (TV) of a literal component is described in terms of code unit values (SV, 11.8.4) contributed by the various parts of the template literal component. As part of this process, some Unicode code points within the template component are interpreted as having a mathematical value (MV, 11.8.3). In determining a TV, escape sequences are replaced by the UTF-16 code unit(s) of the Unicode code point represented by the escape sequence. The Template Raw Value (TRV) is similar to a Template Value with the difference that in TRVs escape sequences are interpreted literally.

And below that, it is defined that:

The TRV of LineTerminatorSequence::<LF> is the code unit 0x000A (LINE FEED).
The TRV of LineTerminatorSequence::<CR> is the code unit 0x000A (LINE FEED).

My interpretation here is, you always just get a line feed – regardless of the OS-specific new-line definitions when you use a template literal.

Finally, in JavaScript’s regular expressions a

n matches a line feed (U+000A).

which describes the observed behavior.

However, if you define a string literal 'rn' or read text from a file stream, etc that contains OS-specific new-lines you have to deal with it.

Here are some tests that demonstrate the behavior of template literals:

`a
b`.split('')
  .map(function (char) {
    console.log(char.charCodeAt(0));
  });

(String.raw`a
b`).split('')
  .map(function (char) {
    console.log(char.charCodeAt(0));
  });
  
 'arnb'.split('')
  .map(function (char) {
    console.log(char.charCodeAt(0));
  });
  
"a
b".split('')
  .map(function (char) {
    console.log(char.charCodeAt(0));
  });

Interpreting the results:
char(97) = a, char(98) = b
char(10) = n, char(13) = r

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement