例如,假设我想将字符串中每个'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正则表达式。
我建议,使用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中的建议 - 评论 - 更正了代码。
参考文献:
对于这样的事情,我个人会选择拆分和测试方法。例如:
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);
有点笨重,但有效。它放弃使用正则表达式语句,所以可能不完全是你正在寻找的。