Check if a JavaScript string is a URL
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:
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.
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.
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.