Skip to content

Instantly share code, notes, and snippets.

@CYBAI
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CYBAI/8c4ec348ca223db417a5 to your computer and use it in GitHub Desktop.
Save CYBAI/8c4ec348ca223db417a5 to your computer and use it in GitHub Desktop.
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