A new method to validate URLs in JavaScript (2023 edition)
- Published at
- Updated at
- Reading time
- 2min
There's news on the URL validation front in JavaScript land! After all these years of cursing JavaScript for not having an easy way to validate a URL, there's a new method in town — URL
!
URL.canParse('https://www.stefanjudis.com'); // true
URL.canParse('www.stefanjudis.com'); // false
Hallelujah! URL
is a quick way to figure out if a string is a valid URL. But before we all get too excited, URL
is not cross-browser supported when writing this post. But you can find up-to-date browser support information below. 👇
![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() |
Nö | Nein | Nö | 115 | 115 | 17 | 17 | Non | Nö |
The static method is already included in core-js
, though. Is it hard work to polyfill the nifty URL validation one-liner? Turns out, nope!
URL
relies on the same algorithm to evaluate a valid URL as the URL()
constructor.
If you're curious and want to level up your spec reading game, URL
and URL()
implement the basic URL parser algorithm that's defined in the WHATWG spec.
And because both methods implement that same parser and URL()
is well supported today, you can follow the general advice to use the constructor to validate URLs. Place new URL()
in a helper function, check if it throws
an exception and call it a day!
function isUrlValid(string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
isUrlValid('https://www.stefanjudis.com'); // true
isUrlValid('www.stefanjudis.com'); // false
Or if you don't fancy an isUrlValid
function, you could also polyfill URL
similar to core-js
.
The only thing remaining is the question "What is a valid URL?" but I'll leave this one for another time! Because it's a tough one.
Yes? Cool! You might want to check out Web Weekly for more web development articles. The last edition went out 16 days ago.