Last active
August 29, 2015 14:13
-
-
Save ducksoupdev/3b2da3f457d062dbf23c to your computer and use it in GitHub Desktop.
Regex indexof methods
This file contains 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
String.prototype.regexIndexOf = function(regex, startpos) { | |
var indexOf = this.substring(startpos || 0).search(regex); | |
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf; | |
} | |
String.prototype.regexLastIndexOf = function(regex, startpos) { | |
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : "")); | |
if(typeof (startpos) == "undefined") { | |
startpos = this.length; | |
} else if(startpos < 0) { | |
startpos = 0; | |
} | |
var stringToWorkWith = this.substring(0, startpos + 1); | |
var lastIndexOf = -1; | |
var nextStop = 0; | |
while((result = regex.exec(stringToWorkWith)) != null) { | |
lastIndexOf = result.index; | |
regex.lastIndex = ++nextStop; | |
} | |
return lastIndexOf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment