How 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 URLs, there's a new method in town โ URL
!
URL.canParse('https://www.stefanjudis.com'); // true
URL.canParse('www.stefanjudis.com'); // false
Hallelujah! URL
offers a quick way to figure out if a string is a valid URL. Can you use it today? Find up-to-date browser support information powered by MDN below. ๐
120 | 120 | 120 | 115 | 115 | 17 | 17 | 25.0 | 120 |
URL
relies on the same algorithm to evaluate a valid URL as the URL()
constructor.
So if the browser support above isn't working for you, could quickly polyfill canParse
similar to how core-js
does it or even write your own isUrlValid
function.
function isUrlValid(string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
isUrlValid('https://www.stefanjudis.com'); // true
isUrlValid('www.stefanjudis.com'); // false
Place the new URL()
call in a helper function, check if it throws
an exception and call it a day!
But what about parsing URLs? Could we remove the try/catch
alltogether?
Apparently, there's also a new WHATWG URL
method that ships in:
Unfortunately, the feature isn't documented on MDN when I updated this article.
In the end, the only question remaining is "What is a valid URL?". But I'll leave this one for another time โ it's a tough one.
Join 5.5k readers and learn something new every week with Web Weekly.