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

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


当前回答

这是@palvo的答案的扩展。

function isValidHttpUrl(string) {
  let url;
  try {
    url = new URL(string);
  } catch (_) {
    return false;  
  }
  return (url.protocol === "http:" || url.protocol === "https:") && (url.href == string || url.origin == string);
}

试试以下方法:-

isValidHttpUrl(“https:母羊/ dsdsd”); isValidHttpUrl(“https://ewe/dsdsd”);

Chrome测试

其他回答

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');

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

function isURL(str) {
  var 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_]*)?$','i'); // fragment locator
  return pattern.test(str);
}

这里还有另一种方法。

// ***note***: if the incoming value is empty(""), the function returns true var elm; function isValidURL(u){ //A precaution/solution for the problem written in the ***note*** if(u!==""){ if(!elm){ elm = document.createElement('input'); elm.setAttribute('type', 'url'); } elm.value = u; return elm.validity.valid; } else{ return false } } console.log(isValidURL('')); console.log(isValidURL('http://www.google.com/')); console.log(isValidURL('//google.com')); console.log(isValidURL('google.com')); console.log(isValidURL('localhost:8000'));

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

你可以简单地在输入中使用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,与上面相同