在JavaScript中,有没有一种方法可以检查字符串是否为URL?
正则表达式被排除在外,因为URL最可能像stackoverflow
这样写,也就是说它可能没有.com
、www
或http
。
在JavaScript中,有没有一种方法可以检查字符串是否为URL?
正则表达式被排除在外,因为URL最可能像stackoverflow
这样写,也就是说它可能没有.com
、www
或http
。
URL
构造函数(如果字符串格式不正确会抛出异常):function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
注意:根据RFC 3886,URL必须以方案开头(不限于http / https),例如:
www.example.com
不是有效的URL(缺少方案)javascript:void(0)
是有效的URL,尽管不是HTTP URLhttp://..
是具有主机..
的有效URL(是否解析取决于您的DNS)https://example..com
是有效的URL,与上述相同href
属性用作 <a>
标签。有效的 URL 必须以方案名称开头,例如 https://
。(参考:https://tools.ietf.org/html/rfc3986#section-1.1.1) - PavloisValidUrl("javascript:void(0)")
。 - Praveenahttp://..
或者 http:///a
。 - aamarks或者这个来自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);
}
https://medium.com/@User_name/
。 - Denis Petrovfunction 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);
}
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
。 - bill davisstart = new Date(); isURL("http://michalstefanow.com"); end = new Date(); diff = end - start; console.log(diff)
我开了水壶,去了趟洗手间,打了个电话给妈妈,结果事情很快就完成了... - Mars Robertsonaaa
,它返回 true
。 - alex naumovisURL('12345678901234567890123')
添加一些更多字符会更糟。 - aamarks与其使用正则表达式,我建议使用锚元素来实现。
当您设置 anchor
的 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);
}
a.href
的URL无效,则parser.host
返回当前页面的主机名,而不是预期的false
。 - Sam Beckhamfunction isValidURL(str)
: 比使用正则表达式要好得多!谢谢! - Rodrigo我正在使用以下函数验证带有或不带有http/https
的URL:
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
https://sdfasdp.ppppppppppp
这个链接上失败了,即返回了true
,但我的答案返回了false
,我认为这是预期的结果。 - Vikasdeep Singhsadf@gmail.com
,它返回的是true...是否应该这样?我想不应该。 - Zohab Ali下面展示如何使用JavaScript验证URL
function ValidURL(str) {
var regex = /(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(str)) {
alert("Please enter valid URL.");
return false;
} else {
return true;
}
}
http
或https
的URL仅用于Web地址。还有许多其他不使用这些方案的URL,它们也是有效的。 - Suncat2000依赖于一个库: https://www.npmjs.com/package/valid-url
import { isWebUri } from 'valid-url';
// ...
if (!isWebUri(url)) {
return "Not a valid url.";
}
{
。 - Willyfrog对已接受答案的改进...
允许路径中包含“@”符号,例如: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);
}
https://www.test
,你可能需要添加以下代码:
if(str.indexOf('www.')>-1 && (str.split('.').length - 1)<2) { return false; }
- Avatar const isUrl = string => {
try { return Boolean(new URL(string)); }
catch(e){ return false; }
}
ES6
import isURL from 'validator/lib/isURL'
isURL(string)
没有 ES6
var validator = require('validator');
validator.isURL(string)
您还可以通过将可选的 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)
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
.kkrieger
^^ - Artfaith
http
,它默认不是一个URL。 - nfechnerhref
解析是否正确、调用window.open(url)
是否有效、指向实际存在的内容、在浏览器地址栏中是否能够工作或以上多种情况的组合对你是否有意义?你将根据你关注的内容得到非常不同的答案。 - Roy Tinker