views:

85

answers:

3
var dateRegex = /\/Date\((\d+)\)\//g;    // [0-9] instead of \d does not help.
dateRegex.test("/Date(1286443710000)/"); // true
dateRegex.test("/Date(1286445750000)/"); // false

Both Chrome and Firefox JavaScript consoles confirm. What the hell, guys?

Edit: even simpler test case:

var dateRegex = /Date\(([0-9]+)\)/g;
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // false
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // false
dateRegex.test("Date(1286445750000)"); // true

This shows that it alternates true/false every time...

A: 

what's the date that you're trying to test?

Musikero31
I've given examples here. It doesn't really matter that it's a date; this is a string problem essentially.
Domenic
The examples are 2010-10-07 09:28:30 and 2010-10-07 10:02:30. Unix time in milliseconds. Not that it matters.
dan04
+7  A: 

In your case remove the g modifier from the end, for example:

var dateRegex = /\/Date\((\d+)\)\//;
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true
dateRegex.test("Date(1286445750000)"); // true

It's a bug with the way regexes are implemented in ECMAScript 3, there's a great post on the details here.

Nick Craver
A bad browser behavior that isn't microsoft's fault? What gives? =)
RMorrisey
@Nick Still no plans to add lookbehind support, heh?
NullUserException
@NullUserException - I don't keep up with this portion of the spec really, some of the regex guys might...but that article is a few years old, though it's the same bug as the OPs seeing. What's on the table for future specs *may* have changed, but nothing I've heard about at least.
Nick Craver
I reached same conclusion that removing g solves it, but thanks @nick I didn't know about faulty implementation.
TheVillageIdiot
A: 

The /g was causing problem. Following code works fine.

<div id="test"></div>
    <script type="text/javascript">
        var reg = /Date\(\d+\)/; //REGEX WITHOUT g
        var d="Date(1286445750000)";
        $(function(){
            var $d=$("div#test");
            for(var i=0;i<100;i++){
                if(reg.test(d)){
                    $d.html($d.html()+"<br/>Matched: ["+d+"]");
                }
                else{
                    $d.html($d.html()+"<br/>Not Matched: ["+d+"]");
                }
            }
        });
    </script>
TheVillageIdiot