How can I replace a match only at a certain position inside the string?

后端 未结 5 1880
盖世英雄少女心
盖世英雄少女心 2020-12-06 02:43

So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?

Example:

5条回答
  •  萌比男神i
    2020-12-06 03:08

    Javascript match returns an array, in case of multiple matches, so you could so something like this:

    var string = "....";
    var patt1 = /..../gi;
    var results = string.match(patt1);
    var newString = results.splice(i, i).join();
    

    Instead of using a match, you could use split instead in your specific case:

    var results = string.split("_");
    var newString = results.splice(i, i).join("_");
    

    It depends on how your input data can vary and where you need to do the split/match (that is why I did not specify any regex above, the split example is complete)...

提交回复
热议问题