Skip to content

Instantly share code, notes, and snippets.

@NV
Created October 6, 2009 17:53
Show Gist options
  • Save NV/203242 to your computer and use it in GitHub Desktop.
Save NV/203242 to your computer and use it in GitHub Desktop.
JavaScript implementation Ruby's str.insert method
/**
* '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