Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the statement if ( !condition ) { console.log(condition) } display true [duplicate]

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.

like image 405
kipenzam Avatar asked Jan 29 '14 08:01

kipenzam


People also ask

What does console log () do?

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.

What is the output of console log Boolean?

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.

Does console log reduce performance?

Using console. log will use CPU cycles. In computing, nothing is "free." The more you log, the slower your code will execute.


1 Answers

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.

  • See also this answer: https://stackoverflow.com/a/3827500/548225 for more details.
like image 64
anubhava Avatar answered Oct 13 '22 06:10

anubhava