Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my date regex? [duplicate]

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

like image 464
Domenic Avatar asked Sep 30 '10 03:09

Domenic


2 Answers

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.

like image 150
Nick Craver Avatar answered Oct 09 '22 08:10

Nick Craver


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>
like image 28
TheVillageIdiot Avatar answered Oct 09 '22 10:10

TheVillageIdiot