In this article, we are going to learn about a string containing a valid URL format. A valid URL should follow the standard format, including the scheme (e.g., “http://” or “https://” ), domain, and optional path, query parameters, and fragments.
There are several methods that can be used to check if a string contains a valid URL format in JavaScript.
Using Regular Expressions. URL constructor Using the URL object available in modern browsers We will explore all the above methods along with their basic implementation with the help of examples.
Regular expressions are a powerful tool to match patterns in strings. We can use a regular expression to check if the string follows the valid URL format.
Syntax:
const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i; Example: In this example, the isValidURL function uses a regex pattern to validate URLs. It returns true for valid URLs, and false otherwise.
Javascript
function isValidURL(url) {
const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return urlPattern.test(url);
}
console.log(isValidURL(
console.log(isValidURL(
console.log(isValidURL("invalid-url"));
Approach 2: Using URL Constructor URL constructor in JavaScript creates a URL object, checks if given string is a valid URL; throws error otherwise.
Syntax:
try { new URL(url); return true; } catch (error) { return false; } Example: In this example, the function uses the URL API to validate URLs. It returns true if valid, false otherwise.
Javascript
function isValidURL(url) {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
}
console.log(isValidURL(
console.log(isValidURL(
console.log(isValidURL("invalid-url"));
Approach 3: Using the URL Object Available in Modern Browsers Modern browsers provide an URL object that can parse a URL string and validate it. This method is generally more reliable and less error-prone.
Syntax:
const urlObject = new URL(url); Example: In this example, we are using the above-explained approach.
Javascript
function isValidURL(url) {
try {
const urlObject = new URL(url);
return true;
} catch (error) {
return false;
}
}
console.log(isValidURL(
console.log(isValidURL(
console.log(isValidURL("invalid-url"));
Last Updated :
01 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...