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

标签 javascript regex

例如,假设我想将字符串中每个“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 is1 a s2imple s3tring to tes4t regex。

最佳答案

我建议使用 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 .

引用资料:

关于javascript - 如何用不同的结果替换文本中所有相同的字符/字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051018/

相关文章:

javascript - 我的 Async/Await (ES2017) 函数没有按顺序运行?

javascript - 如何在 webpack 中加载 paper.js?

javascript - moment.js 中的 isValid() 和 _isValid 有什么区别?

regex - 加快正则表达式匹配?

java - 正则表达式将引号内的文本选择为组

java - 使用 java/regex 查找最后一个匹配项

javascript - 调用添加到函数原型(prototype)的函数

javascript - 运行 Javascript 函数来填充表格,然后使用 Jsoup 解析 HTML 页面

php - 如何知道 laravel 模型值是否在保存回调时更改

c# - 负向查找后面带有未知数量的空格