Categories
JavaScript Answers

How to validate URL using JavaScript?

Spread the love

Sometimes, we want to validate URL using JavaScript.

In this article, we’ll look at how to validate URL using JavaScript.

How to validate URL using JavaScript?

To validate URL using JavaScript, we can use a regex.

For instance, we write

const validateURL = (textVal) => {
  const urlRegex =
    /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi;
  return urlRegex.test(textVal);
};

to define the validateURL function.

In it, we define the urlRegex that matches URLs.

We use (^|\s)((https?:\/\/)?[\w-]+ to match the protocol, colon, and the slashes.

Then the rest of the regex matches the rest of the URL.

g checks for all matches.

And i makes the regex match in a case insensitive manner.

Then we call urlRegex.test to check if textVal is a URL string.

Conclusion

To validate URL using JavaScript, we can use a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *