url/isUrl.jsjavascript
/**
* 判断字符串是否为指定协议的绝对 URL。
* @function isUrl
* @memberof module:url
* @param {*} value 待判断的值
* @param {string[]} [protocols=['http:','https:']] 允许的协议列表,传空数组表示允许所有协议
* @returns {boolean} URL 格式和协议均满足时为 true
* @throws {TypeError} protocols 不是字符串数组时抛出
*/
function isUrl(value, protocols = ['http:', 'https:']) {
if (typeof value !== 'string') return false
if (!Array.isArray(protocols) || protocols.some(protocol => typeof protocol !== 'string')) throw new TypeError('protocols must be a string array')
try {
const url = new URL(value)
return protocols.length === 0 || protocols.includes(url.protocol)
} catch {
return false
}
}
export default isUrl