I want to make a String method, which accepts a RegExp and a callback, then splits String by RegExp, and inserts callback's return in split array. In short, it would do something like this:
"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
=> [a, 2, b, 3, c]
In case the String doesn't match the RegExp, it should return an array, like this:
"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
=> ["a b c d e"]
I wrote this code, but it doesn't work as I thought:
String.prototype.preserveSplitReg = function(reg, func) {
var rtn = [],
that = this.toString();
if (!reg.test(that)) {
console.log(reg, that, reg.test(that));
return [that];
}
...
}
The console.log should be called ONLY when the String doesn't match reg
, right? But sometimes it logs (reg, that, true)
. That troublesome String and reg
were:
"See <url>http://www.w3.org/TR/html5-diff/</url> for changed elements and attributes, as well as obsolete elements and"
/<url>.*?<\/url>/g
console logs true. I can't figure out why. Any help would be highly appreciated.