Created
November 22, 2022 23:11
-
-
Save Sinequanonh/54b849a7142a291a1ce430363aa2f80f to your computer and use it in GitHub Desktop.
is-url.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Expose `isUrl`. | |
*/ | |
module.exports = isUrl; | |
/** | |
* RegExps. | |
* A URL must match #1 and then at least one of #2/#3. | |
* Use two levels of REs to avoid REDOS. | |
*/ | |
var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/; | |
var localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/ | |
var nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/; | |
/** | |
* Loosely validate a URL `string`. | |
* | |
* @param {String} string | |
* @return {Boolean} | |
*/ | |
function isUrl(string){ | |
if (typeof string !== 'string') { | |
return false; | |
} | |
var match = string.match(protocolAndDomainRE); | |
if (!match) { | |
return false; | |
} | |
var everythingAfterProtocol = match[1]; | |
if (!everythingAfterProtocol) { | |
return false; | |
} | |
if (localhostDomainRE.test(everythingAfterProtocol) || | |
nonLocalhostDomainRE.test(everythingAfterProtocol)) { | |
return true; | |
} | |
return false; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment