替换字符串中的每第3个逗号

时间:2013-06-16 03:45:37

标签: javascript string

所以我有字符串:

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

}

2 个答案:

答案 0 :(得分:2)

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

str = str.replace(/([^,],[^,]*?,[^,]*?),/g, '$1!');

答案 1 :(得分:1)

尝试

var str = "blue,red,green,orange,yellow,brown,black,teal,purple,gold,silver"
str = str.replace(/(([^,]*,){2}([^,]*)),/g, '$1!')