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

URL.canParse('https://www.stefanjudis.com'); // true 
URL.canParse('www.stefanjudis.com'); // false

Hallelujah! URL.canParse() is a quick way to figure out if a string is a valid URL. But before we all get too excited, URL.canParse() is not cross-browser supported when writing this post. But you can find up-to-date browser support information below. 👇

MDN Compat Data (source)
Browser support info for canParse() static method
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
NeinNeinNope1151151717NöNope

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

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 14 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.