用于确定电子邮件域的JavaScript RegEx(例如yahoo.com)

AnA*_*ice 4 javascript regex

使用JavaScript我想要输入第一个验证电子邮件是有效的(我解决了这个)第二,验证电子邮件地址来自yahoo.com

有人知道将提供域名的正则表达式吗?

thxs

Tim*_*ker 8

var myemail = 'test@yahoo.com'

if (/@yahoo.com\s*$/.test(myemail)) {
   console.log("it ends in @yahoo");
} 
Run Code Online (Sandbox Code Playgroud)

如果字符串以@yahoo.com(加上可选的空格)结束,则为true .


sty*_*fle 6

您不需要使用正则表达式.

您可以使用该indexOf方法查看字符串是否包含另一个字符串.

var idx = emailAddress.indexOf('@yahoo.com');
if (idx > -1) {
  // true if the address contains yahoo.com
}
Run Code Online (Sandbox Code Playgroud)

我们可以利用slice()这样实现"结束":

var idx = emailAddress.lastIndexOf('@');
if (idx > -1 && emailAddress.slice(idx + 1) === 'yahoo.com') {
  // true if the address ends with yahoo.com
}
Run Code Online (Sandbox Code Playgroud)

在常绿浏览器中,您可以使用内置的String.prototype.endsWith(),如下所示:

if (emailAddress.endsWith('@yahoo.com')) {
    // true if the address ends with yahoo.com
}
Run Code Online (Sandbox Code Playgroud)

有关浏览器支持,请参阅MDN文档.