Last active
August 29, 2015 14:05
-
-
Save westc/15e34f237ff1123f511c to your computer and use it in GitHub Desktop.
Gets the substring after 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 after the specified target. | |
* @param {string|RegExp} target | |
* Specifies the substring to key off in order to pull the substring that | |
* follows it. | |
* @param {number=} opt_occurrence | |
* Optional. The number of the occurrence to key off of. Defaults to 1. | |
* @return {string|null} | |
* If the target is found, the substring that follows will be returned. | |
* Otherwise undefined is returned. | |
*/ | |
String.prototype.after = 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(m) { | |
splits.push(arguments[arguments.length - 2] + m.length); | |
}); | |
} | |
return Math.abs(opt_occurrence = opt_occurrence || 1) > splits.length - !isRegExp | |
? null | |
: isRegExp | |
? this.slice(splits.slice(opt_occurrence - (opt_occurrence > 0))[0]) | |
: splits.slice(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 tests: