Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 29, 2015 14:05
Show Gist options
  • Save westc/15e34f237ff1123f511c to your computer and use it in GitHub Desktop.
Save westc/15e34f237ff1123f511c to your computer and use it in GitHub Desktop.
Gets the substring after the specified target.
/**
* @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);
};
@westc
Copy link
Author

westc commented Jan 17, 2015

Here are some tests:

console.group('Test String.prototype.after()');
console.group('String tests')
console.log('"asdfasdf".after("d", -3) === null:', "asdfasdf".after("d", -3) === null);
console.log('"asdfasdf".after("d", -2) === "fasdf":', "asdfasdf".after("d", -2) === "fasdf");
console.log('"asdfasdf".after("d", -1) === "f":', "asdfasdf".after("d", -1) === "f");
console.log('"asdfasdf".after("d") === "fasdf":', "asdfasdf".after("d") === "fasdf");
console.log('"asdfasdf".after("d", 1) === "fasdf":', "asdfasdf".after("d", 1) === "fasdf");
console.log('"asdfasdf".after("d", 2) === "f":', "asdfasdf".after("d", 2) === "f");
console.log('"asdfasdf".after("d", 3) === null:', "asdfasdf".after("d", 3) === null);
console.groupEnd();
console.group('RegExp tests');
console.log('"asdf".after(/[sD]/i, -3) === null:', "asdf".after(/[sD]/i, -3) === null);
console.log('"asdf".after(/[sD]/i, -2) === "df":', "asdf".after(/[sD]/i, -2) === "df");
console.log('"asdf".after(/[sD]/i, -1) === "f":', "asdf".after(/[sD]/i, -1) === "f");
console.log('"asdf".after(/[sD]/i) === "df":', "asdf".after(/[sD]/i) === "df");
console.log('"asdf".after(/[sD]/i, 1) === "df":', "asdf".after(/[sD]/i, 1) === "df");
console.log('"asdf".after(/[sD]/i, 2) === "f":', "asdf".after(/[sD]/i, 2) === "f");
console.log('"asdf".after(/[sD]/i, 3) === null:', "asdf".after(/[sD]/i, 3) === null);
console.groupEnd();
console.groupEnd();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment