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

后端 未结 5 1881
盖世英雄少女心
盖世英雄少女心 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:23

    Could look like:

    var mystr = 'a_a_a_a_a';
    
    function replaceIndex(string, at, repl) {
       return string.replace(/\S/g, function(match, i) {
            if( i === at ) return repl;
    
            return match;
        });
    }
    
    replaceIndex(mystr, 2, '_');
    

    The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments:

    • the string to modify
    • the index we wish to change
    • the replacement character for that position

提交回复
热议问题