JS Regex url验证

mot*_*s10 9 javascript regex jquery web

我尝试使用或不使用http来验证url无论我做什么函数返回false.我在这个网站上检查了我的正则表达式字符串:http: //regexr.com/ 它看起来像我期待的那样.

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我通过将.test更改为.match来解决问题,并保留正则表达式.

mot*_*s10 21

我将函数更改为Match +使用斜杠及其工作进行更改:(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;
}
Run Code Online (Sandbox Code Playgroud)

  • 应该是`(http(s)?:\ /\/.)?(www \.)?[ - a-zA-Z0-9 @:%._\+〜#=] {2,256} \.[az ] {2,6}\b([ - a-zA-Z0-9 @:%_\+.〜#?&=]*)`.在https://regex101.com/上检查上述正则表达式会出错. (5认同)

Ame*_*icA 8

其实这道题需要强大的力量regex,下面的代码也不是很难理解,请看下面(ES6 - TypeScript):

const isValidUrl = (url: string): boolean => {
  const urlRegex = /^((http(s?)?):\/\/)?([wW]{3}\.)?[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/g;
  const result = url.match(urlRegex);

  return result !== null;
};
Run Code Online (Sandbox Code Playgroud)


m69*_*g'' 5

我相信其他答案会拒绝一些有效的网址(例如大写域名或长子域的域名),并允许一些无效的网址(例如http://www.-example-.com或www.%@&.com)。我试图考虑许多其他url语法规则(不涉及国际化)。

function isUrlValid(userInput) {
    var regexQuery = "^(https?://)?(www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.[a-z]{2,6}(/[-\\w@\\+\\.~#\\?&/=%]*)?$";
    var url = new RegExp(regexQuery,"i");
    return url.test(userInput);
}
var input = ["https://o.sub-domain.example.com/foo/bar?foo=bar&boo=far#a%20b",
             "HTTP://EX-AMPLE.COM",
             "example.c",
             "example-.com"];
for (var i in input) document.write(isUrlValid(input[i]) + ": " + input[i] + "<br>");
Run Code Online (Sandbox Code Playgroud)

为了也允许IP地址和端口号,正则表达式为:

"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\\??.[a-z]{2,6})|((\\d{1??,3}\\.){3}\\d{1,3}))??(:\\d{2,4})?(/[-\\w@??\\+\\.~#\\?&/=%]*)?$??"  
Run Code Online (Sandbox Code Playgroud)

为了也允许查询字符串在域名和问号之间没有斜线(理论上是不允许的,但是在大多数实际情况下都可以使用),正则表达式为:

"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\\??.[a??-z]{2,6})|((\\d??{1,3}\\.){3}\\d{1,3}??))(:\\d{2,4})?((/|\\???)[-\\w@\\+\\.~#\\?&??/=%]*)?$"
Run Code Online (Sandbox Code Playgroud)

为了确保每个%后面都有一个十六进制数字,正则表达式为:

"^(https?://)?(((www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z??0-9]{0,61}[a-z0-9]\\??.[a-z]{2,6})|((\\d{1??,3}\\.){3}\\d{1,3}))??(:\\d{2,4})?((/|\\?)??(((%[0-9a-f]{2})|[-\??\w@\\+\\.~#\\?&/=])*??))?$"
Run Code Online (Sandbox Code Playgroud)

(注意:正如John Wu在评论中提到的那样,存在有效的单字母域名