Published at
Updated at
Reading time

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.canParse()!

URL.canParse(''); // true 
URL.canParse(''); // false

Hallelujah! URL.canParse() 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. ๐Ÿ‘‡

MDN Compat Data (source)
Browser support info for canParse() static method

URL.canParse() 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(''); // true
isUrlValid(''); // 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.parse() 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.

Additional resources

Was this post helpful?
Yes? Cool! You might want to check out Web Weekly for more web development articles. The last edition went out 4 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles