Published on

How to Validate if String is valid URL in JavaScript


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.


// Based on
function isUrl(string) {
	try {
		new URL(string);
		return true;
	} catch {
		return false;

How does it work?

It tries to parse the string as (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!