开发者

What is wrong with my date regex? [duplicate]

开发者 https://www.devze.com 2023-01-18 08:04 出处:网络
This question already has answers here: Why does a RegExp with global flag give wrong 开发者_运维问答results?
This question already has answers here: Why does a RegExp with global flag give wrong 开发者_运维问答results? (7 answers) Closed 7 years ago.
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...


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消