14
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...

Domenic
  • 110,262
  • 41
  • 219
  • 271

2 Answers2

27

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    A bad browser behavior that isn't microsoft's fault? What gives? =) – RMorrisey Sep 30 '10 at 03:35
  • 1
    Still no plans to add lookbehind support, heh? – NullUserException Sep 30 '10 at 03:37
  • @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 Sep 30 '10 at 03:43
  • I reached same conclusion that removing g solves it, but thanks @nick I didn't know about faulty implementation. – TheVillageIdiot Sep 30 '10 at 03:47
1

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
  • 40,053
  • 20
  • 133
  • 188