在JavaScript中是否有一种方法来检查字符串是否是URL?

regex被排除在外,因为URL很可能写成stackoverflow;也就是说,它可能没有。com, WWW或http。


当前回答

这里只是一个非常简单的检查,以确保有一个有效的协议,并且域扩展名必须是两个或更多字符。

is_valid_url = ( $url ) => {

    let $url_object = null;

    try {
        $url_object = new URL( $url );
    } catch ( $error ) {
        return false;
    }

    const $protocol = $url_object.protocol;
    const $protocol_position = $url.lastIndexOf( $protocol );
    const $domain_extension_position = $url.lastIndexOf( '.' );

    return (
        $protocol_position === 0 &&
        [ 'http:', 'https:' ].indexOf( $protocol ) !== - 1 &&
        $domain_extension_position > 2 && $url.length - $domain_extension_position > 2
    );

};

其他回答

你可以使用URL原生API:

  const isUrl = string => {
      try { return Boolean(new URL(string)); }
      catch(e){ return false; }
  }

我使用下面的函数来验证URL是否有http/https:

function isValidURL(string) { var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g); return (res !== null) }; var testCase1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble"; console.log(isValidURL(testCase1)); // return true var testCase2 = "http://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&docid=nIv5rk2GyP3hXM&tbnid=isiOkMe3nCtexM:&ved=0CAUQjRw&url=http%3A%2F%2Fanimalcrossing.wikia.com%2Fwiki%2FLion&ei=ygZXU_2fGKbMsQTf4YLgAQ&bvm=bv.65177938,d.aWc&psig=AFQjCNEpBfKnal9kU7Zu4n7RnEt2nerN4g&ust=1398298682009707"; console.log(isValidURL(testCase2)); // return true var testCase3 = "https://sdfasd"; console.log(isValidURL(testCase3)); // return false var testCase4 = "dfdsfdsfdfdsfsdfs"; console.log(isValidURL(testCase4)); // return false var testCase5 = "magnet:?xt=urn:btih:123"; console.log(isValidURL(testCase5)); // return false var testCase6 = "https://stackoverflow.com/"; console.log(isValidURL(testCase6)); // return true var testCase7 = "https://w"; console.log(isValidURL(testCase7)); // return false var testCase8 = "https://sdfasdp.ppppppppppp"; console.log(isValidURL(testCase8)); // return false

2020年更新。 为了扩展@iamnewton和@ fernando Chavez Herrera的精彩回答,我已经开始看到@被用于url的路径。

所以更新后的正则表达式是:

RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$', 'i');

如果你想在查询字符串和哈希中允许它,使用:

RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$', 'i');

话虽如此,我不确定是否有白皮书规则禁止在查询字符串或哈希中使用@。

该问题询问一个url(如stackoverflow)的验证方法,而没有协议或主机名中的任何点。因此,这不是验证url sintax的问题,而是通过实际调用它来检查它是否是一个有效的url。

我尝试了几种方法来知道url是否真实存在,并且可以从浏览器中调用,但没有找到任何方法来测试javascript调用的响应头:

添加一个锚元素可以触发click()方法。 使用'GET'对具有挑战性的url进行ajax调用是可以的,但由于CORS政策,它有各种限制,并且不是使用ajax的情况,因为url可能在我的服务器域之外。 使用fetch API有一个类似ajax的解决方案。 另一个问题是,我有我的服务器在https协议下,并在调用非安全url时抛出异常。

所以,我能想到的最好的解决方案是得到一些工具来执行CURL使用javascript尝试像CURL -I <url>。不幸的是,我没有找到任何,在外观上,这是不可能的。我将感谢任何关于这一点的评论。

但是,最后,我有一个运行PHP的服务器,因为我几乎所有的请求都使用Ajax,所以我在服务器端编写了一个函数来执行curl请求并返回到浏览器。

关于“stackoverflow”问题上的单个单词url,它将引导我到https://daniserver.com.ar/stackoverflow,其中daniserver.com.ar是我自己的域名。

Mathias Bynens编译了一个带有测试URL的知名URL正则表达式列表。没有什么理由去写一个新的正则表达式;只要选择一个现有的最适合你的。

但是这些正则表达式的比较表也表明,使用单个正则表达式进行URL验证几乎是不可能的。Bynens列出的所有正则表达式都会产生假阳性和假阴性。

我建议您使用现有的URL解析器(例如JavaScript中的新URL('http://www.example.com/')),然后应用您想要对URL响应的解析和规范化形式执行的检查。它的组件。使用JavaScript URL接口还有一个额外的好处,它只接受浏览器真正接受的URL。

您还应该记住,技术上不正确的url仍然可以工作。例如http://w_w_w.example.com/, http://www..example.com/, http://123.example.com/都有一个无效的主机名部分,但我知道的每个浏览器都会试图打开它们而没有抱怨,当你在/etc/hosts/中为这些无效的名称指定IP地址时,这样的url甚至可以工作,但只在你的计算机上。

因此,问题不在于URL是否有效,而在于在特定的上下文中应该允许哪些URL工作。

如果你想进行URL验证,有很多细节和边缘情况很容易被忽视:

URLs may contain credentials as in http://user:password@www.example.com/. Port numbers must be in the range of 0-65535, but you may still want to exclude the wildcard port 0. Port numbers may have leading zeros as in http://www.example.com:000080/. IPv4 addresses are by no means restricted to 4 decimal integers in the range of 0-255. You can use one to four integers, and they can be decimal, octal or hexadecimal. The URLs https://010.010.000010.010/, https://0x8.0x8.0x0008.0x8/, https://8.8.2056/, https://8.526344/, https://134744072/ are all valid and just creative ways of writing https://8.8.8.8/. Allowing loopback addresses (http://127.0.0.1/), private IP addresses (http://192.168.1.1), link-local addresses (http://169.254.100.200) and so on may have an impact on security or privacy. If, for instance, you allow them as the address of user avatars in a forum, you cause the users' browsers to send unsolicited network requests in their local network and in the internet of things such requests may cause funny and not so funny things to happen in your home. For the same reasons, you may want to discard links to not fully qualified hostnames, in other words hostnames without a dot. But hostnames may always have a trailing dot (like in http://www.stackoverflow.com.). The hostname portion of a link may contain angle brackets for IPv6 addresses as in http://[::1]. IPv6 addresses also have ranges for private networks or link-local addresses etc. If you block certain IPv4 addresses, keep in mind that for example https://127.0.0.1 and https://[::ffff:127.0.0.1] point to the same resource (if the loopback device of your machine is IPv6 ready). The hostname portion of URLs may now contain Unicode, so that the character range [-0-9a-zA-z] is definitely no longer sufficient. Many registries for top-level domains define specific restrictions, for example on the allowed set of Unicode characters. Or they subdivide their namespace (like co.uk and many others). Top-level domains must not contain decimal digits, and the hyphen is not allowed unless for the IDN A-label prefix "xn--". Unicode top-level domains (and their punycode encoding with "xn--") must still contain only letters but who wants to check that in a regex?

应用哪些限制和规则取决于项目需求和喜好。

我最近为一个web应用程序编写了一个URL验证器,它适用于论坛、社交网络等用户提供的URL。你可以把它作为你自己的基础:

(Angular)前端的JavaScript/Typescript版本 Perl版本的后端

我还写了一篇博客文章《URL验证的血淋淋的细节》,提供了更深入的信息。