I recently encountered two troubling bugs with jPaq’s String.prototype.indexOfPattern() function.  In order to fix it, I ended up exploring the powerful String.prototype.replace() function, exploiting the parameter passed into the callback function.  I already knew that the matched text and sub-groups were passed into the callback function.  The thing that I didn’t know was that the second-to-the-last parameter passed is the start index of the matched string.  This gave me the idea to create a function which can return an array of all of the matches and sub-groups in object literals, along with the offset and original text.  Instead of me explaining it, take a look:

[sourcecode language=”js”]
function getMatches(str, exp) {
var ret = [];
str.replace(exp, function() {
var match = {length : arguments.length – 2};
for(var i = 0, iOffset = match.length; i < iOffset; i++)
match[i] = arguments[i];
match.offset = arguments[i];
match.original = arguments[i + 1];
ret.push(match);
});
return ret;
}
[/sourcecode]

Categories: BlogJavaScript