Last active
August 29, 2015 14:05
-
-
Save westc/e08687b699784f6e46ff to your computer and use it in GitHub Desktop.
Gets the substring before the specified target.
This file contains hidden or 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
/** | |
* @license Copyright 2015 - Chris West - MIT Licensed | |
* Gets the substring before the specified target. | |
* @param {string|RegExp} target | |
* Specifies the substring to key off in order to pull the substring that | |
* precedes it. | |
* @param {number=} opt_occurrence | |
* Optional. The number of the occurrence to key off of. Defaults to 1. | |
* @return {string=} | |
* If the target is found, the substring that precedes will be returned. | |
* Otherwise undefined is returned. | |
*/ | |
String.prototype.before = function(target, opt_occurrence) { | |
var isRegExp = {}.toString.call(target) == '[object RegExp]', | |
splits = isRegExp ? [] : this.split(target); | |
if (isRegExp) { | |
target = target.global | |
? target | |
: new RegExp(target.source, 'g' + (target.ignoreCase ? 'i' : '') + (target.multiline ? 'm' : '')); | |
this.replace(target, function() { | |
splits.push(arguments[arguments.length - 2]); | |
}); | |
} | |
return Math.abs(opt_occurrence = opt_occurrence || 1) > splits.length - !isRegExp | |
? null | |
: isRegExp | |
? this.slice(0, splits.slice(opt_occurrence - (opt_occurrence > 0))[0]) | |
: splits.slice(0, opt_occurrence).join(target); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are some examples: