【问题标题】:Is there a smarter way to achive replacement with variables in Javascript? [duplicate]有没有更聪明的方法来实现用 Javascript 中的变量替换? [复制]
【发布时间】:2021-07-02 12:18:10
【问题描述】:

我是 Javascript 的初学者,我有以下问题:

我必须用字符串中的相同替换替换模式#XY1、#XY2、#XY3 或#XY4。

例如。替换为 AA:

这是 #XY1 和 #XY3 示例 #XY1 --> 这是 AA 和 AA 示例 AA

模式是随机出现的,字符串中可能有多个(不同的)一次。如何在不频繁迭代字符串的情况下替换它们?所以我不寻找这样的建议:

str = str.replace(/:#XY1:/g, "Replacement")
str = str.replace(/:#XY2:/g, "Replacement")
str = str.replace(/:#XY3:/g, "Replacement")
str = str.replace(/:#XY4:/g, "Replacement")

或带有循环的东西。

我希望找到一个解决方案,我只需遍历字符串一次并替换所有模式#XY 加上下一个变量字符。

由于某些版本问题,我无法使用 .replaceAll。

感谢您的帮助,祝您有美好的一天!干杯,乔什

【问题讨论】:

  • 到目前为止您尝试过什么?你被困在哪里了?这是否总是四个字符串(以XY 开头),后跟数字一到四?
  • 将所有正则表达式组合成一个表达式,例如str = str.replace(/:#XY[1-4]:/g, "Replacement")
  • 要替换的模式始终以#XY 开头,后跟一个数字(1、2、3 或 4)

标签: javascript regex


【解决方案1】:

只需使用一个正则表达式和通配符数字。

const repl = (source, value) => source.replace(/#XY\d/g, value);

console.log(repl('this is #XY1 an #XY3 example #XY1', 'AA')) // this is AA an AA example AA

【讨论】:

    【解决方案2】:

    你可以使用

    /#XY\d/
    

    const str = "this is #XY1 an #XY3 example #XY1";
    const replacement = "AA";
    
    const result = str.replace(/#XY\d/g, replacement);
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 1970-01-01
      • 2022-07-12
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多