javascript - JS 字符串中的行尾(也称为换行符)

标签 javascript regex eol

众所周知,类 Unix 系统使用 LF 字符作为换行符,而 Windows 使用 CR+LF

但是,当我在我的 Windows PC 上从本地 HTML 文件测试这段代码时,似乎 JS 将所​​有换行符视为用 LF 分隔。这是正确的假设吗?

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`?

最佳答案

我想我找到了一个解释。

您正在使用 ES6 Template Literal构造您的多行字符串。

根据ECMAScript specs一个

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

在此之下,定义为:

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

我的解释是,当您使用模板文字时,您总是只得到一个换行符 - 无论操作系统特定的换行符定义如何。

最后,在JavaScript's regular expressions一个

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

它描述了观察到的行为。

但是,如果您定义字符串文字 '\r\n' 或从文件流中读取文本等,其中包含特定于操作系统的换行符,则您必须处理它。

下面是一些演示模板文字行为的测试:

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

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

解释结果:
char(97) = a, char(98) = b
char(10) = \n, char(13) = \r

关于javascript - JS 字符串中的行尾(也称为换行符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968130/

相关文章:

javascript - 字母数字字符和 -/only 的正则表达式

c# - 名称的正则表达式应以字母开头

git - `git` 显示克隆后更改的文件,没有任何其他操作

javascript - 如何水平对齐面板中具有动态大小的按钮

javascript 将标准函数转换为 Promise

javascript - 正则表达式不起作用

php - Notepad++ 将我所有的 PHP 放在一行中

git - 在 git repo 和工作副本中强制 LF eol

javascript - 当 Controller 执行时设置 AngularJS 中元素的高度

javascript - Requirejs组合应用程序window.onerror错误处理