Skip to content Skip to sidebar Skip to footer

What Is Wrong With My Date Regex?

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

Solution 1:

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.

Solution 2:

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

<divid="test"></div><scripttype="text/javascript">var reg = /Date\(\d+\)/; //REGEX WITHOUT gvar 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>

Post a Comment for "What Is Wrong With My Date Regex?"