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

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

问题描述

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



以下是代码:

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

第一次调用replace方法让我很困惑,我不明白$ 1 价值来自或意味着什么。我会认为调用应该用替换找到的模式。

解决方案

每一对括号 ... 第一个字符不是 *是一个捕获组,它将结果放入 $ 1 $ 2 $ 3 等可用于替换模式。



您可能也会看到与相同的内容其他正则表达式引擎中的\ $ \2 \3 (或者实际上在原始表达式中,有时为了重复)



这些被称为反向引用,因为它们通常会引用表达式中的(较早的)部分。 / p>

(* 表示各种形式的特殊行为,包括<$ c $的非捕获组c>(?: ... 并且只是没有捕获的组。)





在您的具体示例中,$ 1将是g roup (^ |)这是字符串起始位置(零宽度)或单个空格字符。



因此,通过用它替换整个表达式,你基本上是删除变量 theClass ,并且可能是后面的空格。 (结束表达式(| $)是反向的 - 空格或字符串结束位置 - 由于未使用其值,因此可能是非捕获(?: | $)代替。)





希望这解释一切正常 - 如果您想了解更多信息,请告诉我。



此外,还有一些来自网站的进一步阅读 regular-expressions.info




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

It's the following code:

Core.removeClass = function(target, theClass)
{
    var pattern = new RegExp("(^| )" + theClass + "( |$)");
    target.className = target.className.replace(pattern, "$1");
    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 think that the call should replace the found pattern with "".

解决方案

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.

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


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

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.

Also, here's some further reading from the site regular-expressions.info:

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

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