JavaScript中用于URL验证的正则表达式

38

是否有一个用于验证URL(而不是在文本中查找它们)的正则表达式?最好使用JavaScript代码片段。

18个回答

1

try with this:

 var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

1
/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/

我认为您的表达式在协议和 // 之间漏掉了一个 :。否则,它可以正常工作! - Gustavo Straube

1

试试这个正则表达式,对我很有效:

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

1
我想确保这个正则表达式不会出现假阴性。你使用它没有遇到问题吗? - Marek Stój
1
目前还没有问题。为什么不对你预期中的误报进行测试呢? - ennuikiller
1
它可能会对查询中的 ';' 这样的符号产生错误的负面结果,除非在表达式的中间有一个大大的 \S+,可以扩展匹配几乎任何字符,而且它没有以结尾为锚点,因此您可以输入任何无关的内容。例如 'http://@' 或 'http://I've got a lovely bunch of "coconuts"' 都是“有效”的。 - bobince

1
我使用 /^[a-z]+:[^:]+$/i 正则表达式来进行URL验证。看看我的跨浏览器 InputKeyFilter 代码示例,其中包含URL验证。

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input Key Filter Test</title>
 <meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 
 <!-- For compatibility of IE browser with audio element in the beep() function.
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>
 
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
 
</head>
<body>
URL: 
<input type="url" id="Url" value=":"/>
<script>
 CreateUrlFilter("Url", function(event){//onChange event
   inputKeyFilter.RemoveMyTooltip();
   var elementNewInteger = document.getElementById("NewUrl");
   elementNewInteger.innerHTML = this.value;
  }
  
  //onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
  , function(event){ this.ikf.customFilter(this); }
 );
</script>
 New URL: <span id="NewUrl"></span>

</body>
</html>

另请参阅我的页面输入键过滤器示例


不起作用。它将此标记为有效。h://google.com - Ata ul Mustafa
h://google.com 是一个有效的URL。"h:"是一个有效的前缀。 有关详细信息,请参见https://www.w3.org/Addressing/URL/url-spec.txt。有效URL的示例: mailto:myname@domain.com https://google.com如果您想仅过滤超文本传输协议,则需要使用/^http://[^:]+$/i正则表达式。 - Andrej

1

我尝试了几个,但出现了一些问题,所以我想出了这个。

/(https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9]+\.[^\s]{2,}|www\d*\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;

如何使用

const isValidUrl = (url = '') => {
    if (url) {
        var expression =
            /(https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9]+\.[^\s]{2,}|www\d*\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;
        var regex = new RegExp(expression);
        return !!url.match(regex);
    }
    return false;
};

细分

/(
  https?:\/\/                        # matches http:// or https://
  (?:www\d*\.|(?!www\d*\.)          # matches an optional "www" prefix with zero or more digits, followed by a dot,
                                    # or excludes "www" prefix followed by digits
  )[a-zA-Z0-9][a-zA-Z0-9-]+          # matches the domain name
  [a-zA-Z0-9]\.                      # matches the dot before the top-level domain
  [^\s]{2,}                          # matches the rest of the URL after the domain name
  |                                 # or
  www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+    # matches the "www" prefix with zero or more digits, followed by a dot, and the domain name
  [a-zA-Z0-9]\.                      # matches the dot before the top-level domain
  [^\s]{2,}                          # matches the rest of the URL after the domain name
  |                                 # or
  https?:\/\/                        # matches http:// or https://
  (?:www\d*\.|(?!www\d*\.)          # matches an optional "www" prefix with zero or more digits, followed by a dot,
                                    # or excludes "www" prefix followed by digits
  )[a-zA-Z0-9]+\.[^\s]{2,}          # matches the domain name and top-level domain
  |                                 # or
  www\d*\.[a-zA-Z0-9]+\.[^\s]{2,}    # matches the "www" prefix with zero or more digits, followed by a dot, and the domain name and top-level domain
)/gi;

有效的URL

http://www.example.com
https://www.example.co.uk
http://www1.example.com
http://www2.example.com
http://www3.example.com
https://www1.example.co.uk
https://www2.example.co.uk
https://www3.example.co.uk
https://example.com
http://example.com
www.example.com
www1.example.com
www2.example.com
www3.example.com
www.example.co.uk
www1.example.co.uk
www2.example.co.uk
www3.example.co.uk

无效的URL

example
example.com
ftp://example.com
ftp://www.example.com
http://www.example
http://www.example.
http://www.example/
http://example./com

0
/^(http|ftp)s?:\/\/((?=.{3,253}$)(localhost|(([^ ]){1,63}\.[^ ]+)))$/

说明:

  1. URL 可以以 http / ftp 开头
  2. 可以跟随 s,但不是必须的
  3. 必须紧接着是 ://
  4. 具有 TLD 的域标签的最大长度为 253。我们在这里看到的是一个查找,以检查总长度最小为 3(即 http://a.b),最大为 253
  5. 然后是 localhostdomain-name.TLD。 domain-name 可以由多个标签组成,用 分隔(例如 https://inner.sub.domain.net), 每个标签的最大长度为 63。 我没有看到 TLD 长度有任何限制,因此我没有在那里设置任何限制。

@bobince的回答是一个真正的问题。

最新的答案非常接近(感谢@Akseli),但它们都错过了URL和长度中必须的。 我提供的答案也解决了这些问题。

更多阅读:


0

来自https://www.freecodecamp.org/news/how-to-validate-urls-in-javascript/

function isValidHttpUrl(str) {
  const pattern = new RegExp(
    '^(https?:\\/\\/)?' + // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
      '(\\#[-a-z\\d_]*)?$', // fragment locator
    'i'
  );
  return pattern.test(str);
}

console.log(isValidHttpUrl('https://www.freecodecamp.org/')); // true
console.log(isValidHttpUrl('mailto://freecodecamp.org')); // false
console.log(isValidHttpUrl('freeCodeCamp')); // false

0
使用纯粹的JavaScript,有时候一个好的方法是使用

标签。
let urlToValidate = `${decodeURIComponent(url)}`

const isValidUrl = (url = '') => {
    try {
        new URL(url);
        return true;
    } catch (error) {
        return false;
    }
};

let result = isValidUrl(urlToValidate)
console.log(result)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接