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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…