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:>
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: