10

我知道在 JavaScript 中,您可以参考捕获组执行正则表达式替换,如下所示:

> "Hello World 1234567890".replace(
        /Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/,
        "What's up $1");
"What's up World"

这一切都很好。但是如果我想引用第 1 组然后紧跟“1”怎么办。说我看什么“世界 1 怎么了”。所以我会写:

> "Hello World 1234567890".replace(
        /Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/,
        "What's up $11");
"What's up 0"

当然,在这种情况下,它引用的是第 11 组,即“0”,而不是第 1 组后跟“1”。

我该如何解决这种歧义?

4

2 回答 2

5

您可以使用String#replace回调函数参数:

str = "Hello World 1234567890";
repl = str.replace(/Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/, function(r, g) {
      return "What's up " + g + '1';});

//=> What's up World1
于 2013-11-07T17:09:05.523 回答
1

不要那样做^^:

(1 + "Hello World 1234567890").replace(
    /(\d)Hello (World) (1)(2)(3)(4)(5)(6)(7)(8)(9)(0)/,
    "What's up $2$1"
);
于 2013-11-07T17:50:23.703 回答