代码之家  ›  专栏  ›  技术社区  ›  theycallmemorty

字符串中的转义数字。代替

  •  -1
  • theycallmemorty  · 技术社区  · 7 年前

    something = mystring.replace(someRegexObject, '$1' + someotherstring);

    someotherstring 有一个数值。。。然后,它与1美元连接,扰乱了组匹配。

    有没有一种简单的方法让我逃离

    1 回复  |  直到 7 年前
        1
  •  3
  •   ctwheels    7 年前

    已解释的问题

    这个问题不是很清楚,但我想我理解你的问题。

    $10 作为捕捉组1的替代品,当且仅当 10

    const regex = /(\w+)/g;
    const str = `something`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, '$10');
    
    console.log('Substitution result: ', result);

    不幸的是,我相信你有一个正则表达式,它捕获了超过 X ( 10 如果您正在查看上述示例)。请参见下面的代码段中返回的值不正确。

    const regex = /(\w+)((((((((()))))))))/g;
    const str = `something`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, '$10');
    
    console.log('Substitution result: ', result);

    解决方案

    const regex = /(\w+)((((((((()))))))))/g;
    const str = `something`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, function(a, b) {
      return b+'0';
    });
    
    console.log('Substitution result: ', result);