Home > Web Front-end > JS Tutorial > body text

Is a JavaScript String a Valid HTTP URL?: A Practical Function for URL Verification

Linda Hamilton
Release: 2024-11-15 05:12:02
Original
508 people have browsed it

Is a JavaScript String a Valid HTTP URL?: A Practical Function for URL Verification

How to Verify a JavaScript String as a URL

In JavaScript, determining if a given string qualifies as a URL can be crucial. Unlike verifying email addresses or telephone numbers, URLs possess a unique mixture of components and possible formats.

To accomplish this task, we'll utilize a URL constructor. This constructor analyzes the provided string and evaluates whether it meets the URL specifications. If the string is malformed or does not adhere to the URL standards, the constructor astutely throws an exception.

Here's a tailored JavaScript function to assess the validity of an HTTP URL:

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

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

This function cleverly analyzes the provided string, subsequently structuring it according to the URL template. If successful, it minutely examines the protocol, ensuring it explicitly conforms to the "http:" or "https:" formats. This precise check guarantees the URL is indeed an HTTP URL.

However, it's imperative to acknowledge that while RFC 3886 proclaims all URLs must commence with a scheme (beyond merely "http" or "https"), this function cautiously confines its validation to HTTP URLs. Notable exceptions include:

  1. "www.example.com" lacks a scheme and is therefore an invalid URL.
  2. "javascript:void(0)" possesses a valid scheme and is thus considered a valid URL, albeit not an HTTP one.
  3. "http://.." is uniquely structured, having a host named ".." whose resolvability depends on the DNS configuration.
  4. "https://example..com" follows the same suit as above.

By employing this function, developers can confidently discern whether a string constitutes a valid HTTP URL, enabling robust and reliable URL handling in their JavaScript applications.

The above is the detailed content of Is a JavaScript String a Valid HTTP URL?: A Practical Function for URL Verification. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template