所以我有字符串:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
您如何用!
(例如)替换每个第三个逗号?它看起来像:
var str = "blue,red,green!orange,yellow,brown!black,teal,purple!gold,silver,white"
在整理了一些我发现的东西之后,我想出了这个:
var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
function replaceIndex(string, at, repl) {
return string.replace(/\S/g, function(match, u) {
if( u === at ) return repl;
return match;
});
var total_items = str.split(",").length - 1;
var counter = 1;
for (var i = 0; i < str.length; i++){
if (str.charAt(i) == ","){
if (total_items%counter == 0){
replaceIndex(str, i, "},{");
}
counter++;
}
}
}