gpt4 book ai didi

javascript - str.replace(/^/gm, "\t") 的预期行为是什么

转载 作者:行者123 更新时间:2023-12-05 01:04:22 27 4
gpt4 key购买 nike

我希望 str.replace(/^/gm, "\t") 在每一行前面插入一个 \t。似乎是这样,但只有在使用 LF 结尾时,在使用 CRLF 结尾时,会发生一些奇怪的事情,它也将其插入到 \r\n 之间。

考虑这个示例代码:

var str1 = "First line\nnext Line";
var str2 = "First line\r\nnext Line";

function escape(str) {
return str.replace(/[\r\n\t]/g, match => {
return {
'\r': '\\r',
'\n': '\\n',
'\t': '\\t',
}[match]
})
}

console.log("First string:")
console.log(escape(str1))


console.log("Second string:")
console.log(escape(str2))

function operation(str) {
return str.replace(/^/gm, "\t");
}

console.log("First string:")
str1 = operation(str1)
console.log(escape(str1))


console.log("Second string:")
str2 = operation(str2)
console.log(escape(str2))
.as-console-wrapper {
max-height: 100% !important;
}

转换后,第一个字符串是预期的\tFirst line\n\tnext Line,但是第二个结果是\tFirst line\r\t\n\tnext Line ,这会在 VScode Extension 中产生意外行为我正在使用。 VSCode 会分别解释每个 \n\r 并用 \n\r 替换每个,这会导致格式不正确。控制台,似乎并不关心,并按预期显示它,因此使用了转义功能,以显示那些讨厌的回车和换行。

这是预期的行为还是 javascript 标准库中的错误?

最佳答案

这完全符合 ECMAScript specification, 22.2.2.4 Runtime Semantics: CompileAssertion :

Assertion :: ^

1. Return a new Matcher with parameters (x, c) that captures nothing and performs
the following steps when called:
a. Assert: x is a State.
b. Assert: c is a Continuation.
c. Let e be x's endIndex.
d. If e = 0, or if Multiline is true and the character Input[e - 1] is one of
LineTerminator, then
i. Return c(x).
e. Return failure.

Elsewhere, in Section 12.3 LineTerminator被定义为 <LF> <CR> <LS> <PS> 之一, 所以 \r\n确实被视为单独的终结者。

可能最简单的解决方法是不使用 m自己标记并匹配所有类型的行尾(包括过去在 Mac 上使用的 \r):

>>> "foo\rbar\r\nbaz\nqux".replace(/(^|\r\n|\r|\n)/g, "$1\t")
"\tfoo\r\tbar\r\n\tbaz\n\tqux"

请注意 \r\n必须在 \r 之前以便它作为一个单元匹配。

关于javascript - str.replace(/^/gm, "\t") 的预期行为是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72110015/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com