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)
Tom*_*len 134
一个相关问题的答案:
或者来自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)
Luk*_*uke 87
我建议使用锚元素,而不是使用正则表达式.
设置href
an 的属性时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)
Pav*_*vlo 75
您可以尝试使用URL
构造函数:如果它不抛出,则该字符串是有效的URL:
const isValidUrl = (string) => {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
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)
小智 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)
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)
Mwi*_*Tim 22
对已接受答案的改进......
允许在路径中使用@符号,例如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)小智 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)
(我没有代表对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的最佳方法.
使用验证器.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)
该函数不允许 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)
我一直用来验证 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)
正如已经指出的那样,完美的正则表达式是难以捉摸的,但似乎仍然是一种合理的方法(替代方案是服务器端测试或新的实验性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本机API:
const isUrl = string => {
try { return Boolean(new URL(string)); }
catch(e){ return false; }
}
Run Code Online (Sandbox Code Playgroud)
我无法评论最接近#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)
使用纯正则表达式很难做到这一点,因为 URL 有很多“不便”。
例如域名对连字符有复杂的限制:
一种。中间允许有多个连续的连字符。
湾 但是域名的首尾字符不能是连字符
C。第三个和第四个字符不能都是连字符
同样,端口号只能在 1-65535 范围内。如果您提取端口部分并转换为,这很容易检查,int
但很难使用正则表达式进行检查。
也没有简单的方法来检查有效的域扩展。一些国家有二级域名(例如“co.uk”),或者扩展名可以是一个长词,例如“.international”。并且会定期添加新的 TLD。这种类型的事情只能根据硬编码列表进行检查。(见https://en.wikipedia.org/wiki/Top-level_domain)
然后是磁铁网址、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)
已经有很多答案了,但这是另一个贡献:直接取自URL
polyfill 有效性检查,使用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 次 |
最近记录: |