Last active
August 29, 2015 14:08
-
-
Save CYBAI/8c4ec348ca223db417a5 to your computer and use it in GitHub Desktop.
Replace character at particular index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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