检查JavaScript字符串是否为URL

Bru*_*uno 222 javascript string url

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

RegExes被排除在外,因为URL最有可能写成stackoverflow; 也就是说它可能没有.com,www或者http.

Zem*_*nik 161

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 它为`aaa`返回`true`. (51认同)
  • 为什么这个答案有143个赞成? (17认同)
  • 失败的谷歌搜索图片链接:`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&乌斯= 1398298682009707` (12认同)
  • 这是无法使用的慢 (3认同)
  • @HernánEche**慢**是什么意思?start = new Date(); isURL(“ http://michalstefanow.com”); 结束=新的Date(); diff =结束-开始;console.log(diff)```我放了水壶,上了厕所,叫我妈妈,事情很快就完成了... (2认同)
  • 这绝对不应该是正确答案。它未能通过许多测试用例,更重要的是它甚至会将您的页面挂在一个短字符串上:`isURL('12345678901234567890123')` 添加更多字符,甚至更糟。 (2认同)

Tom*_*len 134

一个相关问题的答案:

Javascript正则表达式URL匹配

或者来自Devshed的 Regexp :

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 函数返回:`SyntaxError:无效的正则表达式:/^(https?://)?((([azd]([azd-]*[azd])*.)+ [ast] {2,} |((d {1,3}){3} d {1,3}.))(:d +)(/ [ - 一个-ZD%_〜+.]*)*([? ;&a-zd%_.〜+ = - ]*)?(#[ - a-zd _]*)?$ /:无效群组`Google Chrome(版本30.0.1599.101)(Mac OS X:10.8.5) (124认同)
  • 试图用你的例子.但我在firebug上收到一个错误,说"无效量词".任何的想法? (10认同)
  • 请注意,如果使用字符串作为`RegExp`的参数,则必须双重转义反斜杠 - 否则会出现**无效组**等错误. (9认同)
  • 如果我们输入“111111111111111111111111111111111111111111111111”作为输入服务器将挂起。我遇到了这个问题,然后将我的代码更改为 str.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\ +~#=]{2,256}\.[az]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) ; (7认同)
  • 使用 Firefox 52.0.2,测试“长”字符串(实际上没有那么长,40 个字符就足够了)非常慢,以至于我不得不终止脚本。不知道这是 Firefox 的错误还是表达式本身有问题。 (6认同)
  • 有效网址失败 https://web.archive.org/web/20170817095211/https://github.com/Microsoft/vscode/issues/32405 (5认同)
  • 我认为这个答案已经过时,建议不要在生产中使用它 (3认同)
  • @Bruno:它们很可能在内部保存了单独的标题和URL,例如``title:"Stackoverflow",uri:"http://stackoverflow.com"}`**更新:**的确看到http: //code.google.com/chrome/extensions/bookmarks.html (2认同)
  • 在 https://en.m.wikipedia.org/wiki/C_Sharp_(programming_language) 上失败 (2认同)
  • www.jayakumar 这是一个有效的网址吗?它返回 true (2认同)

Luk*_*uke 87

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

设置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"
Run Code Online (Sandbox Code Playgroud)

资源

但是,如果href绑定的值不是有效的URL,则这些辅助属性的值将为空字符串.

编辑:如评论中所指出的:如果使用了无效的网址,则可以替换当前网址的属性.

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

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

  • `function isValidURL(str)`:比使用正则表达式好多了!谢谢! (4认同)
  • 情况并非如此(至少在Chrome 48中).如果传递给`a.href`的url无效,`parser.host`将返回您当前所在页面的主机名,而不是预期的`false`. (3认同)
  • 尔加!那真是怪了.我发誓我测试了这个!我认为可以说这不会在当前页面上使用,所以条件可以改变.我会编辑帖子. (2认同)

Pav*_*vlo 75

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

const isValidUrl = (string) => {
  try {
    new URL(string);
    return true;
  } catch (_) {
    return false;  
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @AshD不,不是; 例如,你不能用作`<a>`的`href`属性.有效的URL [必须以方案名称开头](https://tools.ietf.org/html/rfc3986#section-1.1.1),例如`https://`. (11认同)
  • @Pavlo返回true`isValidUrl("javascript:void(0)")` (6认同)
  • FWIW `new URL('#')` 返回有效 (5认同)
  • 另一个误报是“http://a” (4认同)
  • 对于诸如 www.google.com 之类的字符串,这会引发异常,表明这不是有效的 URL(当它是有效的 URL 时) (3认同)
  • 新网址('javascript:alert(23)') (3认同)
  • 我喜欢这样教我有关js的新知识!我没有发现任何假阴性。它确实有一些误报:“ http:// ..”或“ http:/// a” (3认同)
  • URL从Edge开始运行,因此其下方的所有内容均可能无法正常运行。确保首先检查兼容性。 (2认同)
  • 到目前为止最好的答案 (2认同)
  • 应该是最好的答案。OP要求非正则表达式解决方案 (2认同)
  • `isValidHttpUrl("http://www")` 返回 `true`。 (2认同)

Vik*_*ngh 34

我使用以下函数来验证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
Run Code Online (Sandbox Code Playgroud)

  • 它的返回值是否为`sadf @ gmail.com` ...应该吗?我想应该不会 (4认同)
  • 当 URL 具有端口时,此操作会失败。 (3认同)
  • 似乎是一个不错的解决方案!您是否可以添加一些测试来证明它在某些极端情况下有效(例如,请参见这些[comments](/sf/answers/1020756061/))? (2认同)

小智 31

使用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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 正则表达式的几个部分可以大大减少:a)`(http | https)`到`(?:https?)`; b)`:{0,1}`到`:?`; c)`[0-9]`到`\ d` (3认同)

Mic*_*she 24

依靠图书馆:https: //www.npmjs.com/package/valid-url

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

  • 这给我带来了很多浏览器实际解析的奇怪网址的麻烦,例如:网址中有一个“{” (2认同)

Mwi*_*Tim 22

对已接受答案的改进......

  • 检查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);
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 不,它不应该是公认的答案.像其他一些它只挂在一个33字符的字符串:isURL('123456789012345678901234567890123')和许多边缘案例测试失败:http://foo.com/blah_blah_(wikipedia)_(again)//错误地返回false. (5认同)
  • 这应该是公认的答案。谢谢! (2认同)
  • 那是因为localhost:8080不是有效的URL。 (2认同)

小智 11

这是另一种方法.

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'));
Run Code Online (Sandbox Code Playgroud)


ko *_* la 9

(我没有代表对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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Ily*_*ich 9

使用验证器.js

ES6

import isURL from 'validator/lib/isURL'

isURL(string)
Run Code Online (Sandbox Code Playgroud)

没有 ES6

var validator = require('validator');

validator.isURL(string)
Run Code Online (Sandbox Code Playgroud)

您还可以通过将可选options对象作为第二个参数传递来微调此函数的行为isURL

这是默认options对象:

let options = {
    protocols: [
        'http',
        'https',
        'ftp'
    ],
    require_tld: true,
    require_protocol: false,
    require_host: true,
    require_valid_protocol: true,
    allow_underscores: false,
    host_whitelist: false,
    host_blacklist: false,
    allow_trailing_dot: false,
    allow_protocol_relative_urls: false,
    disallow_auth: false
}

isURL(string, options)
Run Code Online (Sandbox Code Playgroud)

host_whitelist并且host_blacklist可以是主机数组。它们还支持正则表达式。

let options = {
    host_blacklist: ['foo.com', 'bar.com'],
}

isURL('http://foobar.com', options) // => true
isURL('http://foo.bar.com/', options) // => true
isURL('http://qux.com', options) // => true

isURL('http://bar.com/', options) // => false
isURL('http://foo.com/', options) // => false


options = {
    host_blacklist: ['bar.com', 'foo.com', /\.foo\.com$/],
}

isURL('http://foobar.com', options) // => true
isURL('http://foo.bar.com/', options) // => true
isURL('http://qux.com', options) // => true

isURL('http://bar.com/', options) // => false
isURL('http://foo.com/', options) // => false
isURL('http://images.foo.com/', options) // => false
isURL('http://cdn.foo.com/', options) // => false
isURL('http://a.b.c.foo.com/', options) // => false
Run Code Online (Sandbox Code Playgroud)

  • 好的!小型库(压缩后少于 40k)、流行库(npm 上每周下载量超过 300 万次),为您提供了大量的灵活性,可以为您的特定用例指定 URL 的有效性,并且除了 URL 之外还有许多其他验证器。恕我直言,这是迄今为止最好的答案。 (3认同)

Cra*_*lot 9

该函数不允许 localhost 并且只允许网页的 URL(即只允许 http 或 https 协议)。

它还只允许此处定义的安全字符:https : //www.urlencoder.io/learn/

function isValidWebUrl(url) {
   let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
   return regEx.test(url);
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 7

我一直用来验证 URL“字符串”的一个函数是:

var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;

function isUrl(string){
  return matcher.test(string);
}
Run Code Online (Sandbox Code Playgroud)

此函数将返回一个布尔值,无论字符串是否为 URL。

例子:

isUrl("https://google.com");     // true
isUrl("http://google.com");      // true
isUrl("http://google.de");       // true
isUrl("//google.de");            // true
isUrl("google.de");              // false
isUrl("http://google.com");      // true
isUrl("http://localhost");       // true
isUrl("https://sdfasd");         // false
Run Code Online (Sandbox Code Playgroud)


aam*_*rks 7

正如已经指出的那样,完美的正则表达式是难以捉摸的,但似乎仍然是一种合理的方法(替代方案是服务器端测试或新的实验性URL API).然而,对于常见的URL,高排名的答案通常会返回false,但更糟糕的是,即使是简单的字符串,也会冻结您的app/page几分钟isURL('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').在一些评论中已经指出了这一点,但很可能没有看到它的坏价值.像这样挂起使得代码在任何严肃的应用程序中都无法使用.我认为这是由于代码中的重复不区分大小写的集合((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|' ....取出'i'并且它不会挂起但当然不会按预期工作.但即使使用ignore case标志,这些测试也会拒绝允许的高unicode值.

已经提到的最好的是:

function isURL(str) {
  return /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/.test(str); 
}
Run Code Online (Sandbox Code Playgroud)

这来自Github segmentio/is-url.关于代码存储库的好处是你可以看到测试和任何问题以及测试字符串贯穿它.有一个分支可以让字符串丢失协议google.com,尽管你可能做了太多的假设.存储库已更新,我不打算在这里试图保持镜像.它已被分解为单独的测试,以避免可用于DOS攻击的RegEx 重做(我认为你不必担心客户端js,但你必须担心你的页面挂了很长时间,以至于你的访客离开您的网站).

dperini/regex-weburl.js中,我见过的另一个存储库甚至可能对isURL更好,但它非常复杂.它有一个更大的有效和无效URL测试列表.上面简单的一个仍然传递所有的积极因素,并且只能阻止一些奇怪的否定http://a.b--c.de/,以及特殊的ips.

无论你选择哪一个,都可以通过这个函数来运行它,我在dperini/regex-weburl.js上的测试中使用了这个函数,同时使用浏览器的Developer Tools函数.

function testIsURL() {
//should match
console.assert(isURL("http://foo.com/blah_blah"));
console.assert(isURL("http://foo.com/blah_blah/"));
console.assert(isURL("http://foo.com/blah_blah_(wikipedia)"));
console.assert(isURL("http://foo.com/blah_blah_(wikipedia)_(again)"));
console.assert(isURL("http://www.example.com/wpstyle/?p=364"));
console.assert(isURL("https://www.example.com/foo/?bar=baz&inga=42&quux"));
console.assert(isURL("http://?df.ws/123"));
console.assert(isURL("http://userid:password@example.com:8080"));
console.assert(isURL("http://userid:password@example.com:8080/"));
console.assert(isURL("http://userid@example.com"));
console.assert(isURL("http://userid@example.com/"));
console.assert(isURL("http://userid@example.com:8080"));
console.assert(isURL("http://userid@example.com:8080/"));
console.assert(isURL("http://userid:password@example.com"));
console.assert(isURL("http://userid:password@example.com/"));
console.assert(isURL("http://142.42.1.1/"));
console.assert(isURL("http://142.42.1.1:8080/"));
console.assert(isURL("http://?.ws/?"));
console.assert(isURL("http://?.ws"));
console.assert(isURL("http://?.ws/"));
console.assert(isURL("http://foo.com/blah_(wikipedia)#cite-1"));
console.assert(isURL("http://foo.com/blah_(wikipedia)_blah#cite-1"));
console.assert(isURL("http://foo.com/unicode_(?)_in_parens"));
console.assert(isURL("http://foo.com/(something)?after=parens"));
console.assert(isURL("http://?.damowmow.com/"));
console.assert(isURL("http://code.google.com/events/#&product=browser"));
console.assert(isURL("http://j.mp"));
console.assert(isURL("ftp://foo.bar/baz"));
console.assert(isURL("http://foo.bar/?q=Test%20URL-encoded%20stuff"));
console.assert(isURL("http://????.??????"));
console.assert(isURL("http://??.??"));
console.assert(isURL("http://??????.???????"));
console.assert(isURL("http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com"));
console.assert(isURL("http://1337.net"));
console.assert(isURL("http://a.b-c.de"));
console.assert(isURL("http://223.255.255.254"));
console.assert(isURL("postgres://u:p@example.com:5702/db"));
console.assert(isURL("https://d1f4470da51b49289906b3d6cbd65074@app.getsentry.com/13176"));

//SHOULD NOT MATCH:
console.assert(!isURL("http://"));
console.assert(!isURL("http://."));
console.assert(!isURL("http://.."));
console.assert(!isURL("http://../"));
console.assert(!isURL("http://?"));
console.assert(!isURL("http://??"));
console.assert(!isURL("http://??/"));
console.assert(!isURL("http://#"));
console.assert(!isURL("http://##"));
console.assert(!isURL("http://##/"));
console.assert(!isURL("http://foo.bar?q=Spaces should be encoded"));
console.assert(!isURL("//"));
console.assert(!isURL("//a"));
console.assert(!isURL("///a"));
console.assert(!isURL("///"));
console.assert(!isURL("http:///a"));
console.assert(!isURL("foo.com"));
console.assert(!isURL("rdar://1234"));
console.assert(!isURL("h://test"));
console.assert(!isURL("http:// shouldfail.com"));
console.assert(!isURL(":// should fail"));
console.assert(!isURL("http://foo.bar/foo(bar)baz quux"));
console.assert(!isURL("ftps://foo.bar/"));
console.assert(!isURL("http://-error-.invalid/"));
console.assert(!isURL("http://a.b--c.de/"));
console.assert(!isURL("http://-a.b.co"));
console.assert(!isURL("http://a.b-.co"));
console.assert(!isURL("http://0.0.0.0"));
console.assert(!isURL("http://10.1.1.0"));
console.assert(!isURL("http://10.1.1.255"));
console.assert(!isURL("http://224.1.1.1"));
console.assert(!isURL("http://1.1.1.1.1"));
console.assert(!isURL("http://123.123.123"));
console.assert(!isURL("http://3628126748"));
console.assert(!isURL("http://.www.foo.bar/"));
console.assert(!isURL("http://www.foo.bar./"));
console.assert(!isURL("http://.www.foo.bar./"));
console.assert(!isURL("http://10.1.1.1"));}
Run Code Online (Sandbox Code Playgroud)

然后测试那串'a'.

在发布一个看似很棒的正则表达式之前,请参阅Mathias Bynens对isURL正则表达式比较以获取更多信息.

  • 我认为这是一个有效的 URL,在结构上。不是标准专家,但我认为 .com 部分的长度没有限制(我知道 .online 是合法的)。 (2认同)

Ara*_*oca 7

您可以使用URL本机API

  const isUrl = string => {
      try { return Boolean(new URL(string)); }
      catch(e){ return false; }
  }
Run Code Online (Sandbox Code Playgroud)

  • 看起来非常类似于@pavlo提供的答案,只是变量名已更改;) (3认同)
  • 现在真的应该有一个简单的本地方法来检查这个 - 这个答案看起来非常有希望,但正如上面提到的@Basj 一样,它很早就返回 true 。 (2认同)

iam*_*ton 6

我无法评论最接近#5717133的帖子,但下面是我想出如何让@ tom-gullen正则表达式工作的方式.

/^(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
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,但是我需要反斜杠。`var pattern = new RegExp('(https?:\\ / \\ /)?((([[az \\ d]([az \\ d-] * [az \\ d])*)\\。 )+ [az] {2,} |((\\ d {1,3} \\。){3} \\ d {1,3}))(\\:\\ d +)?(\\ / [-az \\ d%_。〜+] *)*(\\?[;&a-z \\ d%_。〜+ =-] *)?(\\#[-az \\ d _] * )?$','i');` (2认同)

Can*_*ner 5

使用纯正则表达式很难做到这一点,因为 URL 有很多“不便”。

  1. 例如域名对连字符有复杂的限制:

    一种。中间允许有多个连续的连字符。

    湾 但是域名的首尾字符不能是连字符

    C。第三个和第四个字符不能都是连字符

  2. 同样,端口号只能在 1-65535 范围内。如果您提取端口部分并转换为,这很容易检查,int但很难使用正则表达式进行检查。

  3. 也没有简单的方法来检查有效的域扩展。一些国家有二级域名(例如“co.uk”),或者扩展名可以是一个长词,例如“.international”。并且会定期添加新的 TLD。这种类型的事情只能根据硬编码列表进行检查。(见https://en.wikipedia.org/wiki/Top-level_domain

  4. 然后是磁铁网址、ftp 地址等。这些都有不同的要求。

尽管如此,这是一个处理几乎所有内容的函数,除了:

  • 案例 1.c
  • 接受任何 1-5 位数字端口号
  • 接受任何扩展 2-13 个字符
  • 不接受ftp、磁铁等...

function isValidURL(input) {
    pattern = '^(https?:\\/\\/)?' + // protocol
        '((([a-zA-Z\\d]([a-zA-Z\\d-]{0,61}[a-zA-Z\\d])*\\.)+' + // sub-domain + domain name
        '[a-zA-Z]{2,13})' + // extension
        '|((\\d{1,3}\\.){3}\\d{1,3})' + // OR ip (v4) address
        '|localhost)' + // OR localhost
        '(\\:\\d{1,5})?' + // port
        '(\\/[a-zA-Z\\&\\d%_.~+-:@]*)*' + // path
        '(\\?[a-zA-Z\\&\\d%_.,~+-:@=;&]*)?' + // query string
        '(\\#[-a-zA-Z&\\d_]*)?$'; // fragment locator
    regex = new RegExp(pattern);
    return regex.test(input);
}

let tests = [];
tests.push(['', false]);
tests.push(['http://en.wikipedia.org/wiki/Procter_&_Gamble', true]);
tests.push(['https://sdfasd', false]);
tests.push(['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', true]);
tests.push(['https://stackoverflow.com/', true]);
tests.push(['https://w', false]);
tests.push(['aaa', false]);
tests.push(['aaaa', false]);
tests.push(['oh.my', true]);
tests.push(['dfdsfdsfdfdsfsdfs', false]);
tests.push(['google.co.uk', true]);
tests.push(['test-domain.MUSEUM', true]);
tests.push(['-hyphen-start.gov.tr', false]);
tests.push(['hyphen-end-.com', false]);
tests.push(['https://sdfasdp.international', true]);
tests.push(['https://sdfasdp.pppppppp', false]);
tests.push(['https://sdfasdp.ppppppppppppppppppp', false]);
tests.push(['https://sdfasd', false]);
tests.push(['https://sub1.1234.sub3.sub4.sub5.co.uk/?', true]);
tests.push(['http://www.google-com.123', false]);
tests.push(['http://my--testdomain.com', false]);
tests.push(['http://my2nd--testdomain.com', true]);
tests.push(['http://thingiverse.com/download:1894343', true]);
tests.push(['https://medium.com/@techytimo', true]);
tests.push(['http://localhost', true]);
tests.push(['localhost', true]);
tests.push(['localhost:8080', true]);
tests.push(['localhost:65536', true]);
tests.push(['localhost:80000', false]);
tests.push(['magnet:?xt=urn:btih:123', true]);

for (let i = 0; i < tests.length; i++) {
    console.log('Test #' + i + (isValidURL(tests[i][0]) == tests[i][1] ? ' passed' : ' failed') + ' on ["' + tests[i][0] + '", ' + tests[i][1] + ']');
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*ger 5

已经有很多答案了,但这是另一个贡献:直接取自URLpolyfill 有效性检查,使用input元素 withtype="url"来利用浏览器的内置有效性检查:

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

if (!inputElement.checkValidity()) {
    throw new TypeError('Invalid URL');
}
Run Code Online (Sandbox Code Playgroud)

来源


归档时间:

查看次数:

257014 次

最近记录:

5 年,9 月 前