Home >Web Front-end >JS Tutorial >Is Your JavaScript String a Valid URL?

Is Your JavaScript String a Valid URL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 17:56:02826browse

Is Your JavaScript String a Valid URL?

How to Determine if a JavaScript String Represents a URL

In JavaScript, you may encounter scenarios where you need to determine if a given string is a valid URL. While regular expressions offer a versatile approach, certain URL formats, such as "stackoverflow," lack standard elements like ".com," "www," or "http."

To handle such cases, a more robust method is utilizing the URL constructor.

Solution:

To check if a string represents a valid HTTP URL, you can employ the following function:

function isValidHttpUrl(string) {
  try {
    const url = new URL(string);
    return url.protocol === "http:" || url.protocol === "https:";
  } catch (_) {
    return false;
  }
}

This function will instantiate a new URL object with the provided string. If the string adheres to the proper URL format, it will succeed without throwing an error.

Note:

It's important to consider that not all URLs must start with "http" or "https." According to RFC 3886, URLs can commence with various schemes. Here are some examples:

  • "www.example.com" is not a valid URL due to the absence of a scheme.
  • "javascript:void(0)" is a valid URL but not an HTTP URL.
  • "http://.." is a valid URL with an unconventional host.
  • "https://example..com" is also a valid URL, with the double period indicative of a non-standard host.

The above is the detailed content of Is Your JavaScript String a Valid URL?. 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