javascript - 奇怪的 Javascript 字符串用 $& 替换行为

标签 javascript regex string replace

使用以下代码:

var x = 'foo';
console.log(x.replace(x, "\\$&"));​

输出为“\foo”,如下所示:http://jsfiddle.net/mPKEx/

为什么不是

'\\$&"?

我将所有 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.

( Reference )

关于javascript - 奇怪的 Javascript 字符串用 $& 替换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12311192/

相关文章:

javascript - 包含 Javascript 的样式并包含非 Javascript 的其他样式

javascript - 如何在 react-router-dom 中实现像 vue-router 这样的路由器离开守卫?

python正则表达式适用于在线测试仪但不适用于程序

javascript - 零到多个范围的正则表达式,例如 : "[12,128]"/ "[45,545][7445,78656]"

r - 排除某个字符串第二次出现后的所有内容

php - 使用php获取字符串的一部分

javascript - 得到Undefine,获得正确输出后显示NaN

javascript - 如何刷新模板中存在的指令并且指令具有自己的数据范围

string - 从多行字符串中删除空行的 Golang 惯用方法

java - 格式化字符串输出