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:
replace('a_a_a_a_a', 1)
Result:
a__a_a_a
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With