首页 > 解决方案 > String.replaceAll 在 JS 的两个参数中使用正则表达式

问题描述

我需要用子字符串的修改版本替换子字符串的所有实例,我可以执行以下操作:

    const regex = /[0-9]{4}[A-Z]{3}/g; // format: 0000ABC
    myString = myString.replaceAll(regex, regex + " I'm modified");

抽象例子

如果 myString 是

5000ABC、250XYZ、GEN3000

我想修改某些 4 位 - 3 个字母的模式,我的预期输出是

5000ABC我改装,250XYZ,1000DEF我改装,GEN3000

标签: javascriptregex

解决方案


我目前的解决方法是

const regex = /[0-9]{4}[A-Z]{3}/g;
var matches = myString.match(regex);
if (matches && matches.length > 0) {
   for (var match of matches) {
      var modified = match + "I'm modified";
      myString = myString.replaceAll(match, modified)
   }
}

推荐阅读