Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replace character at particular index
/**
* String replace character at particular index(es)
* @param {Int or IntArray} index [index to start]
* @param {String} character [character which you want to replace]
* @return {String} [Replaced character]
*/
String.prototype.replaceAt = function(index, character) {
if (typeof index !== 'number' && index instanceof Array !== true) {
throw Error('Please pass a number or an array of number as first argument and your index is ' + index);
}
if (index.length === 1 || typeof index === 'number') {
return this.substr(0, index) + character + this.substr(index + character.length);
} else {
var result = this.toString();
index.forEach(function (val) {
result = result.substr(0, val) + character + result.substr(val + character.length);
});
return result;
}
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.