简体   繁体   English

是否有必要使用正则表达式转义String.replace()调用中的替换字符串?

[英]Is it necessary to escape the replacement string in a String.replace() call with a regular expression?

In wonder if it is necessary to escape certain chars in the replacement string of a replace operation in Javascript. 不知道是否有必要在Javascript中的替换操作的替换字符串中转义某些字符。 What I have is this: 我有的是这个:

let t = "##links##";
let t2 = t.replace(/##links##/, `{"labels": ["'$'"]}`);
console.log(t2);

The console output is: 控制台输出是:

{"labels": ["'"]}

which is pretty surprising. 这非常令人惊讶。 However, I cannot find anything in the documentation that suggests to escape the replacement string. 但是,我在文档中找不到任何建议逃避替换字符串的内容。 So, what's going on here? 那么,这里发生了什么?

You need to double the $ symbol to replace with a literal $ : 您需要将$符号加倍以替换为文字$

 let t = "##links##"; let t2 = t.replace(/##links##/, `{"labels": ["'$$'"]}`); console.log(t2); 

See Specifying a string as a parameter listing all the possible "special" combinations inside a regex replacement part. 请参阅将字符串指定为列出正则表达式替换部件中所有可能的“特殊”组合的参数

If you check that table, you will see that $ starts the "special" sequences. 如果你检查那个表,你会看到$启动“特殊”序列。 Thus, it should be escaped in some way. 因此,它应该以某种方式逃脱。 In JS, a dollar is used to escape the literal dollar symbol. 在JS中,一美元用于逃避文字美元符号。 $& is a backreference to the whole match, $` inserts the portion of the string that precedes the matched substring, $' inserts the portion of the string that follows the matched substring. $&是对整个匹配的反向引用, $`插入匹配子字符串之前的字符串部分, $'插入匹配子字符串后面的字符串部分。 $n is a backrefernece to Group n . $nn组的后退。

So, if you have a dynamic, user-defined replacement string that is not supposed to have backreferences, you may use 因此,如果您有一个动态的,用户定义的替换字符串,不应该有反向引用,您可以使用

 let t = "##links##"; let rep = `{"labels": ["'$'"]}`; let t2 = t.replace(/##links##/, rep.replace(/\\$/g, '$$$$')); console.log(t2); 

Dollar sign ( $ ) is special in replace . 美元符号( $ )特别replace If you want a single, literal dollar sign, use $$ . 如果你想要一个单一的文字美元符号,请使用$$ Otherwise, the replacement string can include the following special replacement patterns : 否则, 替换字符串可以包含以下特殊替换模式

  • $$ Inserts a $ . $$插入一个$
  • $& Inserts the matched substring. $&插入匹配的子字符串。
  • $` Inserts the portion of the string that precedes the matched substring. $`插入匹配子字符串之前的字符串部分。
  • $' Inserts the portion of the string that follows the matched substring. $'插入匹配子字符串后面的字符串部分。
  • $n Where n is a positive integer less than 100, inserts the n th parenthesized submatch string, provided the first argument was a RegExp object. $n其中n是小于100的正整数,插入第n个带括号的子匹配字符串,前提是第一个参数是RegExp对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM