例如,假设我想将字符串中每个“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 .
引用资料:
- Arrow functions .
- “Regular expressions ,” 来自 MDN。
-
String.prototype.replace()
.
关于javascript - 如何用不同的结果替换文本中所有相同的字符/字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051018/