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

How to Validate a URL String in JavaScript Without Regular Expressions?

Susan Sarandon
Release: 2024-11-12 14:18:01
Original
849 people have browsed it

How to Validate a URL String in JavaScript Without Regular Expressions?

Determining the Validity of a URL String in JavaScript

In the realm of JavaScript, the ability to verify whether a given string qualifies as a URL is a crucial skill. Excluding the use of regular expressions, this task can be effectively achieved.

To ascertain if a string represents a valid HTTP URL, the URL constructor offers a reliable solution. This method triggers an error upon encountering an improperly formatted string. Here's a JavaScript function that leverages this approach:

function isValidHttpUrl(string) {
  let url;

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

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

Note: As defined by RFC 3886, a legitimate URL must commence with a scheme (not restricted to HTTP/HTTPS). Consider the following examples:

  • www.example.com: Invalid URL (lacks a scheme)
  • javascript:void(0): Valid URL, but not an HTTP URL
  • http://..: Valid URL with an unusual host (DNS resolution determines accessibility)
  • https://example..com: Valid URL, similar to the previous example

The above is the detailed content of How to Validate a URL String in JavaScript Without Regular Expressions?. 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