Created
October 6, 2009 17:53
-
-
Save NV/203242 to your computer and use it in GitHub Desktop.
JavaScript implementation Ruby's str.insert method
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
/** | |
* 'Hello world'.insert(6, 'happy ') == 'Hello happy world' | |
* 'Hello world'.insert(-1, '!!!') == 'Hello world!!!' | |
* @param at {Number} index | |
* @param text {String} | |
* @see http://ruby-doc.org/core/classes/String.html#M000773 | |
*/ | |
String.prototype.insert = function (at, text) { | |
if (at < 0) { | |
at += this.length + 1; | |
} | |
return this.substr(0, at) + text + this.substr(at); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment