Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 奇数JavasScript字符串替换行为为$&;_Javascript_Regex_String_Replace - Fatal编程技术网

Javascript 奇数JavasScript字符串替换行为为$&;

Javascript 奇数JavasScript字符串替换行为为$&;,javascript,regex,string,replace,Javascript,Regex,String,Replace,使用以下代码: var x = 'foo'; console.log(x.replace(x, "\\$&"));​ 输出为“\foo”,如下所示: 为什么不是呢 '\\$&"? 我正在用“\$&”替换所有的x,这只是一个计划旧字符串,那么为什么string.replace会在函数的第二个参数不应该做任何事情的时候做一些疯狂的替换…$&是Javascript字符串替换中的一个特殊引用。它指向匹配的字符串 $$ - Inserts a "$" $& - Refers to th

使用以下代码:

var x = 'foo';
console.log(x.replace(x, "\\$&"));​
输出为“\foo”,如下所示:

为什么不是呢

'\\$&"?

我正在用“\$&”替换所有的x,这只是一个计划旧字符串,那么为什么string.replace会在函数的第二个参数不应该做任何事情的时候做一些疯狂的替换…

$&是Javascript字符串替换中的一个特殊引用。它指向匹配的字符串

$$ - Inserts a "$" $& - Refers to the entire text of the current pattern match. $` - Refers to the text to the left of the current pattern match. $' - Refers to the text to the right of the current pattern match. $n or $nn - Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. $$-插入一个“$” $&-指当前模式匹配的整个文本。 $`-指当前模式匹配左侧的文本。 $”-指当前模式匹配右侧的文本。 $n或$nn-其中n或nn为十进制数字,插入第n个括号 子匹配字符串,前提是第一个参数是RegExp对象。 ()

在您的情况下:

var x = 'foo';
console.log(x.replace(x, function() {return '\\$&'}));
请看区别:


你可以。上述特殊替换模式($$,$&,$`,$,$n或$nn)在本例中不适用。
Arg是有意义的,这是我正在替换的更大文本字符串的一部分,我花了很长时间才发现这些字符是问题所在,感谢您的帮助!更好的参考:,解释了$syntax的其他变体。奇怪的是,你碰巧选择了这些字符。从你的角度来看,这可能看起来像一个bug。我用一大块碰巧有这些字符的文本替换了一些东西,我花了很长时间才把它缩小到这些字符是原因。我25%的工作是追踪像这样的小秘密。