Home:ALL Converter>Line endings (also known as Newlines) in JS strings

Line endings (also known as Newlines) in JS strings

Ask Time:2018-04-23T00:19:33         Author:john c. j.

Json Formatter

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

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

alert(string);

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

Author:john c. j.,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49968130/line-endings-also-known-as-newlines-in-js-strings
wp78de :

I think I found an explanation.\nYou are using an ES6 Template Literal to construct your multi-line string.\nAccording to the ECMAScript specs a\n\n.. template literal component is interpreted as a sequence of Unicode\ncode points. The Template Value (TV) of a literal component is\ndescribed in terms of code unit values (SV, 11.8.4) contributed by the\nvarious parts of the template literal component. As part of this\nprocess, some Unicode code points within the template component are\ninterpreted as having a mathematical value (MV, 11.8.3). In\ndetermining a TV, escape sequences are replaced by the UTF-16 code\nunit(s) of the Unicode code point represented by the escape sequence.\nThe Template Raw Value (TRV) is similar to a Template Value with the\ndifference that in TRVs escape sequences are interpreted literally.\n\nAnd below that, it is defined that:\n\nThe TRV of LineTerminatorSequence::<LF> is the code unit 0x000A (LINE\nFEED).\nThe TRV of LineTerminatorSequence::<CR> is the code unit 0x000A (LINE FEED).\n\nMy interpretation here is, you always just get a line feed - regardless of the OS-specific new-line definitions when you use a template literal.\nFinally, in JavaScript's regular expressions a\n\n\\n matches a line feed (U+000A).\n\nwhich describes the observed behavior.\nHowever, if you define a string literal '\\r\\n' or read text from a file stream, etc that contains OS-specific new-lines you have to deal with it.\nHere are some tests that demonstrate the behavior of template literals:\n\r\n\r\n`a\nb`.split('')\n .map(function (char) {\n console.log(char.charCodeAt(0));\n });\n\n(String.raw`a\nb`).split('')\n .map(function (char) {\n console.log(char.charCodeAt(0));\n });\n \n 'a\\r\\nb'.split('')\n .map(function (char) {\n console.log(char.charCodeAt(0));\n });\n \n\"a\\\nb\".split('')\n .map(function (char) {\n console.log(char.charCodeAt(0));\n });",
2018-04-23T19:57:57
yy