JS Regex网址验证 [英] JS Regex url validation
本文介绍了JS Regex网址验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论我执行了什么操作,该函数都返回false,我都尝试使用或不使用http来验证url. 我在此网站上检查了我的正则表达式字符串: http://regexr.com/ 和我期望的一样.
I tried to validate url with or without http No matter what i did the function return false. I checked my regex string in this site: http://regexr.com/ And its seen as i expect.
function isUrlValid(userInput) {
var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
var url = new RegExp(regexQuery,"g");
if (url.test(userInput)) {
alert('Great, you entered an E-Mail-address');
return true;
}
return false;
}
我通过将.test更改为.match并保留正则表达式来解决该问题.
I fix the problem by change the .test to .match and leave the regex as is.
推荐答案
我将功能更改为Match +,并在此处使用斜杠及其工作进行更改:(http(s)?://.)
I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)
固定功能:
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
这篇关于JS Regex网址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文