Javascript 替换方法,替换为“$1"; [英] Javascript replace method, replace with "$1"

查看:33
本文介绍了Javascript 替换方法,替换为“$1";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Sitepoints 2007 的书Simply Javascript",但遇到了一些我无法理解的代码.

I'm reading Sitepoints 2007 book "Simply Javascript" and I encountered some code I just can't understand.

代码如下:

Core.removeClass = function(target, theClass)
{
    var pattern = new RegExp("(^| )" + theClass + "( |$)");
    target.className = target.className.replace(pattern, "$1");
    target.className = target.className.replace(/ $/, "");
};

对 replace 方法的第一次调用让我感到困惑,我不明白$1"值从何而来或意味着什么.我会认为调用应该用"替换找到的模式.

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 think that the call should replace the found pattern with "".

推荐答案

每对括号 (...) 其中第一个字符不是 ?* 是一个捕获组",将其结果放入$1$2$3等中,可以使用在替换模式中.

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,3 in other regex engines, (or indeed in the original expression sometimes, for repetition)

这些被称为反向引用",因为它们通常引用表达式中的(更早的)部分.

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.)


在您的具体示例中, $1 将是组 (^| ) ,即字符串开头的位置(零宽度)或单个空格字符".


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".

因此,通过用它替换整个表达式,您基本上是删除了变量 theClass 以及它后面可能的一个空格.(结束表达式 ( |$) 是相反的 - 一个空格或字符串结束位置 - 因为它的值没有被使用,所以可以用 (?: |$) 代替.)

So by replacing the whole expression with that, you're basically removing the variable theClass and 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.)


希望这可以解释一切 - 如果您需要更多信息,请告诉我.


Hopefully this explains everything ok - let me know if you want any more info.

另外,这里有一些来自网站regular-expressions.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)

这篇关于Javascript 替换方法,替换为“$1";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆