Home >Web Front-end >JS Tutorial >Is a JavaScript String a Valid URL: How to Determine?

Is a JavaScript String a Valid URL: How to Determine?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-18 21:58:02781browse

Is a JavaScript String a Valid URL: How to Determine?

How to Determine if a JavaScript String is a URL

When working with JavaScript strings, it can be crucial to verify whether they represent valid URLs. One may be tempted to dismiss regular expressions due to the potential for URLs to lack common components like ".com" or "www," but there are more robust methods available.

Using the URL Constructor for HTTP Validation

If you specifically need to check for valid HTTP URLs, consider utilizing the URL constructor:

function isValidHttpUrl(string) {
  let url;

  try {
    url = new URL(string);
  } catch (_) {
    return false;  
  }

  return url.protocol === "http:" || url.protocol === "https:";
}

This approach throws an exception for malformed URLs, ensuring reliability. It also adheres to RFC 3886 by verifying the presence of a scheme at the beginning of the URL.

Additional Considerations for URL Validity

It's important to note that URLs follow specific rules beyond having an HTTP scheme:

  • They must not begin with a scheme (e.g., "www.example.com" is invalid)
  • Any scheme is permitted (e.g., "javascript:void(0)" is valid, albeit not HTTP)
  • The host can be unconventional (e.g., "http://.." or "https://example..com")

The above is the detailed content of Is a JavaScript String a Valid URL: How to Determine?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn