Skip to content
the poor coder

Check if a JavaScript string is a URL

Poor Man
Published
Reading time
2 min read
On this page

Checking if a JavaScript string is a URL#

As a blogger, I often deal with URLs and links on my website. One of the important tasks is to check if a string is a valid URL or not. Here are a few ways to achieve this in JavaScript.

Method 1: Regular expression#

One way to check if a string is a URL is by using a regular expression. Regular expressions are patterns used to match character combinations in strings. Here's an example of a regular expression to match URLs:

Text

const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
const url = "https://www.example.com";
if (urlRegex.test(url)) {
  console.log("Valid URL");
} else {
  console.log("Invalid URL");
}

The above code defines a regular expression that matches URLs starting with "http://" or "https://" or "ftp://". It then tests if the given string matches this pattern and prints the result.

Method 2: Using the URL constructor#

An alternative way to check if a string is a URL is by using the URL constructor. This method requires the string to be a valid URL, otherwise an exception is thrown.

Text

try {
  const url = new URL("https://www.example.com");
  console.log("Valid URL");
} catch(e) {
  console.log("Invalid URL");
}

The above code creates a new URL object with the given string and catches any exceptions that occur. If the string is a valid URL, then it prints "Valid URL", otherwise it prints "Invalid URL".

Method 3: Using a regular expression package#

If you don't want to write your own regular expression, you can use a package like validator.js which provides a method to check if a string is a URL.

Text

const validator = require('validator');
const url = "https://www.example.com";
if (validator.isURL(url)) {
  console.log("Valid URL");
} else {
  console.log("Invalid URL");
}

The above code imports the validator package and uses its isURL() method to check if the given string is a valid URL. It then prints the result.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC