DEV Community

noothan
noothan

Posted on

URL Validation In JavaScript

URL Validation in JavaScript (2023 edition)

Introduction

For many years, there has been no easy way to validate URLs in JavaScript. However, with the introduction of the URL.canParse() method, this is no longer the case.

URL.canParse()

URL.canParse() is a static method on the URL constructor. It takes a URL string as input and returns true if the URL is valid and false otherwise.

To use URL.canParse(), simply pass the URL string to the method. For example:


javascript
const url = "https://www.stefanjudis.com/blog/validate-urls-in-javascript/";

if (URL.canParse(url)) {
  console.log("The URL is valid.");
} else {
  console.log("The URL is invalid.");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs