1

URL validation checks if a given text is a URL or not. Such checks are often performed when a user has to enter a URL on a web form. To ensure that the entered text corresponds to a URL, I tried to implement the regex like this

regexurl = “((http|https)://)(www.)?” + “[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]” + “{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)”

But I am getting error, Please help where I am being wrong Thanks in advance

Rifky Niyas
  • 1,063
  • 5
  • 20

1 Answers1

2

If your runtime supports it, the better way of validating URLs is using the URL constructor. You can then use the parsed object to verify parts of it separately. For example, to check if something is a valid HTTP(s) URL:

function isValidHttpUrl(s) {
  let url;
  try {
    url = new URL(s);
  } catch (e) { return false; }
  return /https?/.test(url.protocol);
}

isValidHttpUrl("banana"); // false, not a URL
isValidHttpUrl("http://example.com"); // true, is an HTTP URL
isValidHttpUrl("ftp://example.com"); // false, wrong protocol
gustafc
  • 27,774
  • 7
  • 71
  • 98