如何用不同的结果替换文本中所有相同的字符/字符串?

问题描述 投票:2回答:2

例如,假设我想将字符串中每个's'的索引号附加到's'。

var str = "This is a simple string to test regex.";
    var rm = str.match(/s/g);
    for (let i = 0;i < rm.length ;i++) {
        str = str.replace(rm[i],rm[i]+i);
    }
    console.log(str);

输出:This43210是一个测试正则表达式的简单字符串。预期输出:This0是一个s2imple s3tring到tes4t正则表达式。

javascript regex
2个回答
5
投票

我建议,使用replace()

let i = 0,
    str = "This is a simple string to test regex.",
  // result holds the resulting string after modification
  // by String.prototype.replace(); here we use the
  // anonymous callback function, with Arrow function
  // syntax, and return the match (the 's' character)
  // along with the index of that found character:
  result = str.replace(/s/g, (match) => {
    return match + i++;
  });
  console.log(result);

Ezra中的建议 - 评论 - 更正了代码。

参考文献:


2
投票

对于这样的事情,我个人会选择拆分和测试方法。例如:

var str = "This is a simple string to test regex.";
var split = str.split(""); //Split out every char
var recombinedStr = "";
var count = 0;
for(let i = 0; i < split.length; i++) {
  if(split[i] == "s") {
    recombinedStr += split[i] + count;
    count++;
  } else {
    recombinedStr += split[i];
  }
}
console.log(recombinedStr);

有点笨重,但有效。它放弃使用正则表达式语句,所以可能不完全是你正在寻找的。

© www.soinside.com 2019 - 2024. All rights reserved.