Reputation: 94
HTML:
<input type="text" id="txt" value="15228868227"><button id="btn">check</button>
JavaScript:
//email
var rMail = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/g;
//phone
var rPhone = /^(13[0-9]|15[0236789]|18[8|9])\d{8}$/g;
document.getElementById('btn').onclick = function(){
var sTxt = document.getElementById('txt').value;
var bMail = rMail.test(sTxt);
var bPhone = rPhone.test(sTxt);
if(bMail || bPhone){
alert('phone number or email')
};
// console.log(!rMail.test(sTxt) && !rPhone.test(sTxt));
if(!bMail && !bPhone){
alert('Neither phone number nor the emial')
};
};
When I click the button, the first time the result is 'phone number or email' — that's what I want. Then I didn't change anything, just clicked again, and the result is 'Neither phone number nor the emial'! And if I removed comments, the result is always 'phone number or email'. Why?
Upvotes: 2
Views: 44
Reputation: 414016
Get rid of the g
option on your regex. It's affecting the behavior.
The g
option means that you want the regular expression to remember where the previous match ended, and that you want it to start there in the search string for the next match. You clearly don't need that behavior in your code.
You can verify this by looking at the .lastIndex
property of the regular expression object. After the first successful match, it will have a non-zero value. That value is interpreted as where in the search string to start the next time a match is attempted. Because the .lastIndex
is maintained on the regex object itself, the fact that you're testing against a potentially different search string is basically ignored.
Oh, and the reason that your console.log()
call made it work is that when the .lastIndex
value is beyond the end of the string, it starts back over at 0
!
Upvotes: 2