使用JavaScript校驗(yàn)URL的方法小結(jié)
1.使用 URL 構(gòu)造函數(shù)來(lái)驗(yàn)證 URL
當(dāng)傳遞一個(gè)字符串給 URL 構(gòu)造函數(shù)時(shí),如果字符串是一個(gè)有效的 URL,將返回一個(gè)新的 URL 對(duì)象。否則,將返回一個(gè)錯(cuò)誤。
const url = new URL('../cats', 'http://www.example.com/dogs');
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
在控制臺(tái)得到的 URL 對(duì)象:

當(dāng)傳遞一個(gè)無(wú)效的 URL 字符串:
const exampleUrl = new URL('example');
console.log(exampleUrl);
字符串 'example' 不是一個(gè)有效的 URL。因此,會(huì)報(bào)錯(cuò) TypeError:

1.1 使用 URL 構(gòu)造函數(shù)創(chuàng)建一個(gè) URL 驗(yàn)證器函數(shù)
使用 URL 構(gòu)造函數(shù)和 try...catch 語(yǔ)句,創(chuàng)建一個(gè)函數(shù):
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
如果參數(shù)是一個(gè)有效的 URL 時(shí),isValidUrl 函數(shù)返回 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 構(gòu)造器只驗(yàn)證 HTTP URL
要檢查url是否是一個(gè)有效的 HTTP URL,不要其他有效的 URL,如 'mailto://mail@example.com'。
要檢查url是否是一個(gè)有效的 HTTP URL,可以使用 URL 對(duì)象的 protocol 屬性:
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 包來(lái)驗(yàn)證 URL
NPM 包:is-url 和 is-url-http
2.1 使用 is-url 包驗(yàn)證 URL
使用 is-url 包來(lái)檢查一個(gè)字符串是否是一個(gè)有效的 URL。這個(gè)包并不檢查傳遞給它的 URL 的協(xié)議。
安裝:
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 包來(lái)驗(yàn)證 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 來(lái)驗(yàn)證 URL
使用正則表達(dá)式來(lái)檢查一個(gè)url是否是有效的 URL
所有有效的 URL 都遵循一個(gè)特定的模式。它們有三個(gè)主要部分,分別是:
協(xié)議
域名(或 IP 地址)
端口和路徑
有時(shí)路徑后面是一個(gè)查詢字符串或片段定位符。
3.1 使用正則驗(yàn)證 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 使用正則驗(yàn)證 HTTP URL
要使用正則來(lái)檢查一個(gè)url是否是有效的 HTTP URL,需要使用協(xié)議檢查。
使用 '^(https?:\/\/)?',而不是 ^([a-zA-Z]+:\/\/)?:
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校驗(yàn)URL的方法小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于JavaScript校驗(yàn)URL的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript中forEach和map的使用場(chǎng)景
本文JavaScript中forEach和map的使用場(chǎng)景,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
onbeforeunload與onunload事件異同點(diǎn)總結(jié)
本文對(duì)onbeforeunload與onunload事件的異同點(diǎn)、觸發(fā)于、可以用在哪些元素以及解決刷新頁(yè)面時(shí)不調(diào)用onbeforeunload等等,感興趣的朋友可以參考下哈2013-06-06
JS簡(jiǎn)單獲取當(dāng)前日期時(shí)間的方法(如:2017-03-29 11:41:10 星期四)
這篇文章主要介紹了JS簡(jiǎn)單獲取當(dāng)前日期時(shí)間的方法,涉及javascript針對(duì)當(dāng)前日期時(shí)間的簡(jiǎn)單運(yùn)算操作,需要的朋友可以參考下2017-03-03
JS實(shí)現(xiàn)可點(diǎn)擊展開(kāi)與關(guān)閉的左側(cè)廣告代碼
這篇文章主要介紹了JS實(shí)現(xiàn)可點(diǎn)擊展開(kāi)與關(guān)閉的左側(cè)廣告代碼,通過(guò)鼠標(biāo)onClick事件調(diào)用自定義javascript函數(shù)實(shí)現(xiàn)頁(yè)面元素及樣式的顯示與隱藏效果,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-09-09
實(shí)現(xiàn)js保留小數(shù)點(diǎn)后N位的代碼
最近在做項(xiàng)目的時(shí)候,遇到要保留小數(shù)點(diǎn)后N位的問(wèn)題,經(jīng)過(guò)一番思索,最終完成了,這里記錄一下,下次需要直接就能拉出來(lái)用了2014-11-11

