检查 JavaScript 字符串是否为 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5717093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:34:30  来源:igfitidea点击:

Check if a JavaScript string is a URL

javascriptstringurl

提问by Bruno

Is there a way in JavaScript to check if a string is a URL?

JavaScript 中有没有办法检查字符串是否是 URL?

RegExes are excluded because the URL is most likely written like stackoverflow; that is to say that it might not have a .com, wwwor http.

正则表达式被排除在外,因为 URL 很可能是这样写的stackoverflow;也就是说,它可能没有.com,wwwhttp

采纳答案by Tom Gullen

A related question with an answer:

一个相关的问题和答案:

Javascript regex URL matching

Javascript 正则表达式 URL 匹配

Or this Regexp from Devshed:

或者来自Devshed 的这个正则表达式

function validURL(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);
}

回答by Zemljoradnik

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

回答by Pavlo

You can try to use URLconstructor: if it doesn't throw, the string is a valid URL:

您可以尝试使用URL构造函数:如果它没有抛出,则该字符串是一个有效的 URL:

function isValidUrl(string) {
  try {
    new URL(string);
  } catch (_) {
    return false;  
  }

  return true;
}

The term 'URL' is defined in RFC 3886(as URI); it must begin with a scheme name, and the scheme name is not limited to http/https.

术语“URL”在RFC 3886 中定义(作为 URI);必须以方案名开头,方案名不限于http/https。

Notable examples:

值得注意的例子:

  • www.google.comis not valid URL (missing scheme)
  • javascript:void(0)is valid URL, although not an HTTP one
  • http://..is valid URL, with the hostbeing ..; whether it resolves depends on your DNS
  • https://google..comis valid URL, same as above
  • www.google.com不是有效的 URL(缺少方案)
  • javascript:void(0)是有效的 URL,虽然不是 HTTP 的
  • http://..是有效的 URL,主机..; 它是否解析取决于您的 DNS
  • https://google..com是有效的 URL,同上

If you want to check whether a string is a valid HTTP URL:

如果要检查字符串是否是有效的 HTTP URL:

function isValidHttpUrl(string) {
  let url;

  try {
    url = new URL(string);
  } catch (_) {
    return false;  
  }

  return url.protocol === "http:" || url.protocol === "https:";
}

回答by Luke

Rather than using a regular expression, I would recommend making use of an anchor element.

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

when you set the hrefproperty of an anchor, various other properties are set.

当您设置hrefan的属性时,会设置anchor各种其他属性。

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"

source

来源

However, if the value hrefis bound to is not a valid url, then the value of those auxiliary properties will be the empty string.

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

Edit:as pointed out in the comments: if an invalid url is used, the properties of the current URL may be substituted.

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

So, as long as you're not passing in the URL of the current page, you can do something like:

因此,只要您不传入当前页面的 URL,您就可以执行以下操作:

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

回答by Vikasdeep Singh

I am using below function to validate URL with or without http/https:

我正在使用下面的函数来验证有或没有的 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

回答by kavitha Reddy

To Validate Url using javascript is shown below

使用 javascript 验证 URL 如下所示

function ValidURL(str) {
  var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
  if(!regex .test(str)) {
    alert("Please enter valid URL.");
    return false;
  } else {
    return true;
  }
}

回答by Michael Bushe

Rely on a library: https://www.npmjs.com/package/valid-url

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

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

回答by Mwirabua Tim

Improvement on the accepted answer...

改进已接受的答案...

  • Check for ftp/ftps as protocol
  • Has double escaping for backslashes (\\)
  • Ensures that domains have a dot and an extension (.com .io .xyz)
  • Allows full colon (:) in the path e.g. http://thingiverse.com/download:1894343
  • Allows ampersand (&) in path e.g http://en.wikipedia.org/wiki/Procter_&_Gamble
  • Allows @ symbol in path e.g. https://medium.com/@techytimo

    isURL(str) {
      var pattern = new RegExp('^((ft|htt)ps?:\/\/)?'+ // protocol
      '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name and extension
      '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
      '(\:\d+)?'+ // port
      '(\/[-a-z\d%@_.~+&:]*)*'+ // path
      '(\?[;&a-z\d%@_.,~+&:=-]*)?'+ // query string
      '(\#[-a-z\d_]*)?$','i'); // fragment locator
      return pattern.test(str);
    }
    
  • 检查 ftp/ftps 作为协议
  • 对反斜杠 (\\) 进行双重转义
  • 确保域有一个点和一个扩展名 (.com .io .xyz)
  • 允许在路径中使用完整的冒号 (:),例如http://thingiverse.com/download:1894343
  • 允许在路径中使用&符号(&),例如http://en.wikipedia.org/wiki/Procter_&_Gamble
  • 允许在路径中使用@ 符号,例如https://medium.com/@techytimo

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

回答by Ryan Breece

Here is yet another method.

这是另一种方法。

var elm;
function isValidURL(u){
  if(!elm){
    elm = document.createElement('input');
    elm.setAttribute('type', 'url');
  }
  elm.value = u;
  return elm.validity.valid;
}

console.log(isValidURL('http://www.google.com/'));
console.log(isValidURL('//google.com'));
console.log(isValidURL('google.com'));
console.log(isValidURL('localhost:8000'));

回答by ko la

(I don't have reps to comment on ValidURLexample; hence post this as an answer.)

(我没有代表对ValidURL示例发表评论;因此将此作为答案发布。)

While use of protocol relative URLs is not encouraged (The Protocol-relative URL), they do get employed sometimes. To validate such an URL with a regular expression the protocol part could be optional, e.g.:

虽然不鼓励使用协议相对 URL(The Protocol-relative 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;
    }
}

As others noted, regular expression does not seem to be the best suited approach for validating URLs, though.

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