Published on

How to Validate if String is valid URL in JavaScript

Authors

If you have a string and want to validate if it's a valid string or not, then here is how to do it without using any external packages.

Snippet

// Based on https://github.com/sindresorhus/is-url-superb
function isUrl(string) {
	try {
		new URL(string);
		return true;
	} catch {
		return false;
	}
}

How does it work?

It tries to parse the string as (URL)(https://developer.mozilla.org/en-US/docs/Web/API/URL) and if it succeed then it's a valid URL. If not, it's not a valid URL

Alternatively, you can also use is-url-superb package that handles validation and it's a little more flexible.

Happy validating URL!