【发布时间】:2015-02-04 16:47:10
【问题描述】:
我正在使用正则表达式来验证 JavaScript 中的电子邮件地址。
正则表达式非常简单。它检查三件事:1)'@', 2)'.' (something@gmail.com 中的“点”),以及 3) 电子邮件地址中的“a-z”。如果所有三个都返回 true,则电子邮件地址有效(至少根据我的验证)
代码如下:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/@/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
我的问题是:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
即使字符串中没有点也返回 false。
例如:
("thisIsMyEmail".match(/./ig))==null //returns false
为什么它应该为真却返回假?
【问题讨论】:
-
句点在正则表达式中是特殊的,它表示“任何字符”,而不仅仅是句点,要使其表示句点,必须对其进行转义。
-
不要将
match用于文字字符串,而应使用String.prototype.indexOf()
标签: javascript regex