【问题标题】:dollar-sign and a single quote breaks JavaScript string replacement [duplicate]美元符号和单引号会破坏 JavaScript 字符串替换 [重复]
【发布时间】:2020-03-01 14:03:42
【问题描述】:

Javascript 代码:

var testStr = "this is inside the {replace} expression";
var test2Str = "second $ short";
var test3Str = "third '$' short";
var test4Str = "third '$ ' short";
var test5Str = "third $' short";
var test6Str = "third '$$' short";
var test7Str = testStr.replace('{replace}', test2Str);
var test8Str = testStr.replace('{replace}', test3Str);
var test9Str = testStr.replace('{replace}', test4Str);
var test10Str = testStr.replace('{replace}', test5Str);
var test11Str = testStr.replace('{replace}', test6Str);

console.log("test2Str: " + test2Str);
console.log("test3Str: " + test3Str);
console.log("test4Str: " + test4Str);

console.log("test5Str: " + test5Str);
console.log("test6Str: " + test6Str);
console.log("test7Str: " + test7Str);
console.log("test8Str: " + test8Str);
console.log("test9Str: " + test9Str);
console.log("test10Str: " + test10Str);
console.log("test11Str: " + test11Str);

产生:

test2Str: second $ short
test3Str: third '$' short
test4Str: third '$ ' short
test5Str: third $' short
test6Str: third '$$' short
test7Str: this is inside the second $ short expression
test8Str: this is inside the third ' expression short expression
test9Str: this is inside the third '$ ' short expression
test10Str: this is inside the third  expression short expression
test11Str: this is inside the third '$' short expression

由于某种原因,'$ 导致替换函数将替换字符串分成两部分:一部分在正确的位置被替换,另一部分在整个字符串的末尾。这种行为在 Chrome 和 node v10.16.2 命令行中是相同的。有任何想法吗?是否还有其他可能导致类似问题的转义字符?

【问题讨论】:

标签: javascript node.js google-chrome


【解决方案1】:

.replace() 方法将替换字符串中的$ 视为一个元字符,用于指示正​​则表达式中的捕获组值。如果你想要一个简单的$,替换字符串应该包括$$

More details here on MDN.

【讨论】:

  • 尖尖的,非常感谢您的快速回复!好的,所以这似乎是奇怪的行为,并且可能不一致。对于我列出的上述示例:(1)$ 插入 $ 而不是文档所述。 (2) $' 说它应该插入匹配子字符串后面的字符串部分,但结果是拆分了参数字符串,并在参数之前和之后复制了目标字符串的其余部分。文档中对此进行了解释吗? (3) 在没有列出这些特殊模式的情况下进行替换的论点似乎是个好主意?
  • 鉴于 JavaScript 几乎是整个 Internet 的基础,因此得出结论认为 JavaScript 的工作方式是正确和有意的通常是个好主意,即使令人惊讶。
  • 嗯没有。一个更好的答案刚刚发布在这个类似问题的底部:stackoverflow.com/questions/9423722/…。基本上,使用 function() 参数作为替换字符串。它在文档中。不错的 API,非常完美。
猜你喜欢
  • 2011-12-07
  • 2012-09-21
  • 2020-11-30
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 2013-07-19
  • 2015-11-29
相关资源
最近更新 更多