使用JavaScript校验URL的方法小结
本文总结了JavaScript中校验URL的三种主要方法。首先介绍利用原生URL构造函数结合try...catch进行基础验证及HTTP协议过滤;其次推荐通过npm安装is-url和is-url-http包实现更便捷的校验;最后讲解基于正则表达式的复杂URL模式匹配,涵盖协议、域名、IP及路径等要素。
1.使用 URL 构造函数来验证 URL
当向 URL 构造函数传入一个字符串时,若该字符串符合有效 URL 格式,则返回一个新的 URL 对象;否则将抛出错误。
const url = new URL('../cats', 'http://www.example.com/dogs');
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
在控制台输出的 URL 对象示例如下:

当传入无效的 URL 字符串时:
const exampleUrl = new URL('example');
console.log(exampleUrl);
字符串 'example' 并非有效 URL,因此会触发 TypeError 错误:

1.1 使用 URL 构造函数创建一个 URL 验证器函数
结合 URL 构造函数与 try...catch 语句,可以构建如下验证函数:
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
若参数为有效 URL,则 isValidUrl 函数返回 true;否则返回 false:
console.log(isValidUrl('https://www.example.com/')); // true
console.log(isValidUrl('mailto://mail@example.com')); // true
console.log(isValidUrl('freecodecamp')); // false
浏览器兼容性:
该方法在大多数主流浏览器中均得到支持。

1.2 使用 URL 构造器只验证 HTTP URL
如需仅检查 URL 是否为有效的 HTTP 地址,而排除其他协议(如 'mailto://mail@example.com'):
可通过检查 URL 对象的 protocol 属性来实现 HTTP URL 的验证:
function isValidHttpUrl(string) {
try {
const newUrl = new URL(string);
return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';
} catch (err) {
return false;
}
}
console.log(isValidUrl('https://www.example.com/')); // true
console.log(isValidUrl('mailto://mail@example.com')); // false
console.log(isValidUrl('freecodecamp')); // false
2.使用 npm 包来验证 URL
相关的 NPM 包包括:is-url 和 is-url-http
2.1 使用 is-url 包验证 URL
利用 is-url 包可检测字符串是否为有效 URL。需注意,该包不校验 URL 的协议类型。
安装命令如下:
npm install is-url --save使用示例:
import isUrl from 'is-url';
const firstCheck = isUrl('https://kikobeats.com'); // true
const secondCheck = isUrl('mailto://kiko@beats.com'); // true
const thirdCheck = isUrl('example'); // false
2.2 使用 is-url-http 包来验证 HTTP URL
安装命令:
npm install is-url-http --save
使用示例:
import isUrlHttp from 'is-url-http';
isUrlHttp('https://kikobeats.com') // ==> true
isUrlHttp('https://kikobeats.com') // ==> true
isUrlHttp('mailto://kiko@beats.com') // ==> false
isUrlHttp('callto:192.168.103.77+type=ip') // ==> false
3.使用 Regex 来验证 URL
通过正则表达式检查 url 是否有效。
所有有效 URL 均遵循特定模式,主要包含三个部分:
协议 域名(或 IP 地址) 端口和路径 有时路径后还会跟随查询字符串或片段定位符。
3.1 使用正则验证 URL
function isValidUrl(str) {
const pattern = new RegExp(
'^([a-zA-Z]+:\\/\\/)?' + // 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_]*)?$', // fragment locator
'i'
);
return pattern.test(str);
}
console.log(isValidUrl('https://www.kikobeats.com/')); // true
console.log(isValidUrl('mailto://kikobeats.com')); // true
console.log(isValidUrl('example')); // false
3.2 使用正则验证 HTTP URL
若需通过正则表达式检查 url 是否为有效的 HTTP URL,必须加入协议检查逻辑。
将 '^([a-zA-Z]+:\/\/)?' 替换为 '^(https?:\/\/)?':
function isValidHttpUrl(str) {
const 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_]*)?$', // fragment locator
'i'
);
return pattern.test(str);
}
console.log(isValidUrl('https://www.kikobeats.com/')); // true
console.log(isValidUrl('mailto://kikobeats.com')); // false
console.log(isValidUrl('example')); // false
以上就是使用JavaScript校验URL的方法小结的详细内容,更多关于JavaScript校验URL的资料请关注本站其它相关文章!
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
