示例:使用正则表达式
// program to validate an email address
function validateEmail(email_id) {
const regex_pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex_pattern.test(email_id)) {
console.log('The email address is valid');
}
else {
console.log('The email address is not valid');
}
}
validateEmail('[email protected]');
validateEmail('hello@com');
输出
The email address is valid The email address is not valid
在上面的程序中,正则表达式模式
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
检查电子邮件地址是否有效。
test()
方法在 字符串 中找到与正则表达式模式匹配项时返回 true
。
正则表达式 (regex) 描述了一系列用于定义搜索模式的字符。