search

Home  >  Q&A  >  body text

javascript - Problem with regular expression g

When adding g, the button is clicked for the first time and true is returned. When the button is clicked again, false is returned. Why?
The result returned when g is not added is correct.

        window.onload=function(){
            var aInput=document.getElementsByTagName('input');
            var re = /^1\d{10}$/;
            //var re== /^1\d{10}$/g;
            aInput[1].onclick=function(){
                if(re.test(aInput[0].value)){
                    console.log('是电话号码');
                }else{
                    console.log('不是电话号码');
                }
            }
        }
黄舟黄舟2810 days ago556

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:47:29

    http://blog.csdn.net/leolu007...

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:47:29

    /g means global matching. Generally, this parameter is used when replacing all matches with a regular expression.
    However!
    Your regular expression plus /g can also correctly match 11-digit numbers starting with 1. The reason why it is false is that there is an extra equal sign in your code...

    //var re== /^1\d{10}$/g;

    Use the console to execute this line of JS:

    reply
    0
  • Cancelreply