views:

127

answers:

1

Please take a look at the following JavaScript. I've taken stuff out of it, so you may focus on the essence of the problem.

You'll notice that I call the prepPath function twice in a row, passing in the exact same string. In firefox and IE8, this function alerts true each time (as expected). But, in Chromium 5.0.375.127 (55887) Ubuntu 10.04, the function returns true the first time, and false the 2nd call, despite the input remaining exactly the same!

<script type="text/javascript"> 
    function prepPath(str)
    {   
        var regX = /[^\s/"'\\].*[^\s/"'\\]/g;
        if(regX.test(str))
        {
            alert("true: " + str);
        }
        else
        {
            alert("false; " + str);
        }
    }

    prepPath("/desktop"); // alerts: true
    prepPath("/desktop"); // alerts: false 
</script> 

Why is it returning false the second time in Chromium?

+14  A: 

There's some ambiguity in the spec about when literal regexes should get reset (recall that they have state). You can work around this by doing this:

var regX = new RegExp(/[^\s/"'\\].*[^\s/"'\\]/g);

live example: http://jsbin.com/irate

or this:

var regX = /[^\s/"'\\].*[^\s/"'\\]/g;
regX.lastIndex = 0;

live example: http://jsbin.com/irate/2

I'm informed by those who've looked into it more than I have that it's not actually an outright bug, but an ambiguity. And it's not just Chrome, some versions of other browsers have also had a similar problem.

T.J. Crowder
That worked; thank you. Unusual, though. Normally, when you use "var" before setting the value of a variable (in a function), the variable is a new one anyway and only maintains function level scope with zero state between calls.
LonnieBest
@LonnieBest: Oh, it's unusual alright, and it certainly looks wrong, doesn't it? It has to do with the literal and when they're instantiated, and there really is an argument that the literal is instantiated *once* and then reused, strange though it looks. It's the only example of this weird behavior I know of, if that's any consolation. :-)
T.J. Crowder
It's actually the spec that requires this behavior: http://bclary.com/2004/11/07/#a-7.8.5. There's a Chromium bug about it: http://code.google.com/p/chromium/issues/detail?id=2161.
lawnsea
If I had wanted that RegEx object to maintain state, I would have declared it outside of the function. I think the Chromium v8 team ought step inline with firefox and IE on this one, despite the spec ambiguity.
LonnieBest
@LonnieBest: Agreed on both counts. Since this was known before the 5th edition spec was finalized, I kind of hope the new spec clarifies it but I haven't gotten into it to that depth.
T.J. Crowder