0

所以我有字符串:

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++;
    }
}

}

4

2 回答 2

2

您可以使用一些正则表达式魔术来做到这一点:

str = str.replace(/([^,],[^,]*?,[^,]*?),/g, '$1!');
于 2013-06-16T03:57:22.383 回答
1

尝试

var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){2}([^,]*)),/g, '$1!')
于 2013-06-16T03:57:59.087 回答