andy-h
2/5/2014 - 6:50 PM

String.prototype.prune() is the opposite of String.prototype.slice(). It removes the specified portion of the string and returns what's left

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
		}
	};
}