Javascript 替换方法,替换为“$1”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3235763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript replace method, replace with "$1"
提问by Niels Bom
I'm reading Sitepoints 2007 book "Simply Javascript" and I encountered some code I just can't understand.
我正在阅读 Sitepoints 2007 的书“Simply Javascript”,但遇到了一些我无法理解的代码。
It's the following code:
它是以下代码:
Core.removeClass = function(target, theClass)
{
var pattern = new RegExp("(^| )" + theClass + "( |$)");
target.className = target.className.replace(pattern, "");
target.className = target.className.replace(/ $/, "");
};
The first call to the replace method is what puzzles me, I don't understand where the "$1" value comes from or what it means. I would thinkthat the call should replace the found pattern with "".
第一次调用 replace 方法让我感到困惑,我不明白“$1”值从何而来或意味着什么。我认为调用应该用“”替换找到的模式。
回答by Peter Boughton
Each pair of parentheses (...)where the first character is not a ?* is a "capturing group", which places its result into $1,$2,$3,etc which can be used in the replacement pattern.
每对括号(......)其中第一个字符不是?* 是一个“捕获组”,它将其结果放入可以在替换模式中使用的$1, $2, $3, 等。
You might also see the same thing as \1,\2,\3in other regex engines, (or indeed in the original expression sometimes, for repetition)
你可能也看到了同样的事情\1,\2,\3其他正则表达式引擎(或者实际上在原来的表达有时,对于重复)
These are called "backreferences", because they generally refer back to (an earlier) part of in the expression.
这些被称为“反向引用”,因为它们通常返回到表达式中的(较早的)部分。
(*The ?indicates various forms of special behaviour, including a non-capturing group which is (?:...)and simply groups without capturing.)
(*?表示各种形式的特殊行为,包括一个非捕获组,它是(?:......)和简单的没有捕获的组。)
In your specific example, the $1 will be the group (^| )which is "position of the start of string (zero-width), or a single space character".
在您的具体示例中, $1 将(^| )是“字符串开头的位置(零宽度)或单个空格字符”的组。
So by replacing the whole expression with that, you're basically removing the variable theClassand potentially a space after it. (The closing expression ( |$)is the inverse - a space or the string end position - and since its value isn't used, could have been non-capturing with (?: |$)instead.)
因此,通过用它替换整个表达式,您基本上是在删除变量,theClass并可能在它之后删除一个空格。(结束表达式( |$)是相反的 - 一个空格或字符串结束位置 - 因为它的值没有被使用,所以可以用非捕获(?: |$)代替。)
Hopefully this explains everything ok - let me know if you want any more info.
希望这可以解释一切 - 如果您需要更多信息,请告诉我。
Also, here's some further reading from the site regular-expressions.info:
另外,这里有一些来自网站正则表达式.信息的进一步阅读:
- Groups and Backreferences
- Atomic Grouping(doesn't work in JS, but interesting)
- Lookaround groups(partial support in JS regex)
回答by Dagg Nabbit
$1 is a backreference. It will be replaced by whatever the first matching group (set of parenthesis) in your regex matches.
$1 是反向引用。它将被正则表达式匹配中的第一个匹配组(括号集)替换。

