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

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


当前回答

如果你可以改变输入类型,我认为这个解决方案会更容易:

你可以简单地在输入中使用type="url",并在js中使用checkValidity()检查它

E.g:

your.html

<input id="foo" type="url">

your.js

// The selector is JQuery, but the function is plain JS
$("#foo").on("keyup", function() {
    if (this.checkValidity()) {
        // The url is valid
    } else {
        // The url is invalid
    }
});

其他回答

如果你想检查一个字符串是否是有效的HTTP URL,你可以使用URL构造函数(它会抛出一个畸形的字符串):

函数isValidHttpUrl(string) { 让url; 尝试{ url =新的url(字符串); } catch (_) { 返回错误; } 返回的url。Protocol === "http:" || url。协议=== "https:"; } console.log (" http://example.com " + isValidHttpUrl (" https://example.com ")); console.log (" example.com " + isValidHttpUrl (" example.com "));

注意:根据RFC 3886, URL必须以一个方案开头(不限于http/https),例如:

www.example.com不是有效的URL(缺少方案) void(0)是有效的URL,但不是HTTP URL http://.。是有效的URL,主机是..(是否解析取决于你的DNS) https://example..com是有效的URL,与上面相同

依赖库: https://www.npmjs.com/package/valid-url

import { isWebUri } from 'valid-url';
// ...
if (!isWebUri(url)) {
    return "Not a valid url.";
}

已经有很多答案了,但这里有另一个贡献: 直接从URL polyfill有效性检查中获取,使用type=" URL "的输入元素来利用浏览器内置的有效性检查:

var inputElement = doc.createElement('input');
inputElement.type = 'url';
inputElement.value = url;

if (!inputElement.checkValidity()) {
    throw new TypeError('Invalid URL');
}

(我没有代表对ValidURL的例子发表评论;因此,把这个作为一个答案。)

虽然不鼓励使用协议相对URL(协议相对URL),但有时确实会使用它们。要用正则表达式验证这样的URL,协议部分可以是可选的,例如:

function isValidURL(str) {
    var pattern = new RegExp('^((https?:)?\\/\\/)?'+ // protocol
        '(?:\\S+(?::\\S*)?@)?' + // authentication
        '((([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_]*)?$','i'); // fragment locater
    if (!pattern.test(str)) {
        return false;
    } else {
        return true;
    }
}

正如其他人指出的那样,正则表达式似乎不是验证url的最佳方法。

我建议使用锚元素,而不是使用正则表达式。

当你设置一个锚的href属性时,其他各种属性也会被设置。

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

但是,如果href绑定的值不是一个有效的url,那么这些辅助属性的值将是空字符串。

编辑:正如评论中指出的:如果使用了无效的url,则可以替换当前url的属性。

所以,只要你没有传递当前页面的URL,你可以这样做:

function isValidURL(str) {
   var a  = document.createElement('a');
   a.href = str;
   return (a.host && a.host != window.location.host);
}