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.
The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
So by this logic console. log() prints first truthy expression in your statement. If you were to try console. log(null || 2) , then 2 would be printed out.
Using console. log will use CPU cycles. In computing, nothing is "free." The more you log, the slower your code will execute.
This is due to a bug in Javascript RegEx engine (ECMAScript3)
Basically a regex with the g
modifier doesn't reset correctly, so multiple test()
calls toggle between true and false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With