How can I check if a JavaScript string is a valid URL?

How do I check if a JavaScript string is a valid URL using regular expressions or any other built-in methods?

Using a URL constructor, you can check if a string is a valid HTTP URL. This method attempts to create a new URL object from the string. If the string is a valid URL, the method will return a new URL object; if the string is not a valid URL, it will throw an error.

function isValidURL(string) {
  let url;
  try {
    url = new URL(string);
  } catch (e) {
    return false;
  }
  return url.protocol === "http:" || url.protocol === "https:";
}

Alternatively, you can use a regular expression. Define a pattern that matches the structure of a valid URL. You can then use the RegExp constructor to create a new regular expression object and test the string against the pattern using the test() method.

function isValidURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}