How to detect whether a string is in URL format using JavaScript?

Sometimes, we want to detect whether a string is in URL format using JavaScript.

In this article, we’ll look at how to detect whether a string is in URL format using JavaScript.

How to detect whether a string is in URL format using JavaScript?

To detect whether a string is in URL format using JavaScript, we can use a regex.

For instance, we write:

const isUrl = (s) => {
  const regexp = /(ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?/
  return regexp.test(s);
}

console.log(isUrl('http://example.com'))
console.log(isUrl('abc'))

to define the isUrl function to check if the string s matches the /(ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?/ regex with test.

We check if s starts with 'ftp', 'http', or 'https'.

And then we check if there’re colon, 2 slashes, 'www' and characters after that.

Therefore, we see true and false logged.

Conclusion

To detect whether a string is in URL format using JavaScript, we can use a regex.