Home  >  Article  >  Web Front-end  >  Is There a Robust, Regex-Free Way to Validate URLs in JavaScript?

Is There a Robust, Regex-Free Way to Validate URLs in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 21:34:03605browse

Is There a Robust, Regex-Free Way to Validate URLs in JavaScript?

Robust URL Validation in JavaScript

JavaScript provides several useful tools for manipulating and validating strings. In this article, we will specifically focus on checking whether a given string represents a valid URL, excluding the use of regular expressions.

Determining Validity

To determine the validity of a URL, we can utilize the URL constructor. When encountering a malformed URL, this constructor will throw an error. Here's a JavaScript function that employs this approach:

However, it's important to note that this method only checks for the presence of a scheme (e.g., "http" or "https"), as defined by RFC 3886. Therefore, the following scenarios are considered valid URLs:

  • www.example.com (scheme is missing)
  • javascript:void(0) (non-HTTP scheme)
  • http://.. (host is "..")
  • https://example..com (host includes "..")

The above is the detailed content of Is There a Robust, Regex-Free Way to Validate URLs in JavaScript?. 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