Last active
December 22, 2015 17:31
-
-
Save SeanJM/d8a57d9ded98019e3c84 to your computer and use it in GitHub Desktop.
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
// A function to return an array of indexes for a matching string. | |
// Usage : indexesOf('this, this this', 'this'); | |
// Usage : indexesOf('this, this this', /t[a-z]{3}/); | |
// -> [{"index":0,"length":4,"match":"this"}, | |
// {"index":6,"length":4,"match":"this"}, | |
// {"index":11,"length":4,"match":"this"}] | |
// | |
// The 'and' method: | |
// Usage : indexesOf('this, this this', /t[a-z]{3}/).and(/i/); | |
// -> [{"index":0,"length":4,"match":"this"}, | |
// {"index":6,"length":4,"match":"this"}, | |
// {"index":11,"length":4,"match":"this"}, | |
// {"index":2,"length":1,"match":"i"}, | |
// {"index":8,"length":1,"match":"i"}, | |
// {"index":13,"length":1,"match":"i"}] | |
function indexesOf(string, match) { | |
var index = 0; | |
var indexes = []; | |
var max = string.length; | |
function isRegularExpression() { | |
var currentIndex = string.substr(index, max - index).search(match); | |
var matchedString = string.match(match); | |
if (matchedString) { | |
matchedString = matchedString[0]; | |
while (currentIndex !== -1 && index < max) { | |
indexes.push({ | |
index : index + currentIndex, | |
length : matchedString.length, | |
match : matchedString | |
}); | |
index += currentIndex + matchedString.length; | |
currentIndex = string.substr(index, max - index).search(match); | |
if (currentIndex !== -1) { | |
matchedString = string.substr(index, max - index).match(match)[0]; | |
} | |
} | |
} | |
} | |
function isString() { | |
var currentIndex = string.substr(index, max - index).indexOf(match); | |
while (currentIndex !== -1 && index < max) { | |
indexes.push({ | |
index : index + currentIndex, | |
length : match.length, | |
match : match | |
}); | |
index += currentIndex + match.length; | |
currentIndex = string.substr(index, max - index).indexOf(match); | |
} | |
} | |
function and(match) { | |
indexes = indexes.concat(indexesOf(string, match)); | |
indexes.and = and; | |
return indexes; | |
} | |
if (typeof match === 'string') { | |
isString(); | |
} else if (typeof match.test === 'function') { | |
isRegularExpression(); | |
} | |
indexes.and = and; | |
return indexes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment