Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active August 29, 2015 13:56
Show Gist options
  • Save wizard04wsu/8830480 to your computer and use it in GitHub Desktop.
Save wizard04wsu/8830480 to your computer and use it in GitHub Desktop.
String.prototype.prune() is the opposite of String.prototype.slice(). It removes the specified portion of the string and returns what's left, without modifying the original string.
//returns a copy of a string with a portion removed
//(essentially the opposite of `slice`)
//the `end` argument is optional
//str.prune(begin[, end])
if(!String.prototype.prune){
String.prototype.prune = function prune(begin, end){
"use strict";
var newStr = this.slice(0); //make a copy of the string
//make `begin` a positive index
if(!begin) begin = 0;
else if(begin < 0) begin = Math.max(0, this.length+begin);
//try to make `end` a positive index
if(isUndefined(end)) end = this.length;
else if(!end) end = 0;
else if(end < 0) end = this.length+end;
if(end < begin){
return newStr.slice(end, begin); //remove specified elements
}
else{
return newStr.slice(0, begin) + newStr.slice(end); //remove specified elements
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment