How to Check if a String Contains a Valid URL Format in JavaScript ?
Last Updated :
05 May, 2025
A string containing a valid URL format adheres to standard conventions, comprising a scheme (e.g., "http://" or "https://"), domain, and optionally, a path, query parameters, and fragments. Ensuring this format is crucial for data consistency and accurate handling of URLs in applications.
There are several methods that can be used to check if a string contains a valid URL format in JavaScript.
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using Regular Expressions
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(
"https://www.geeksforgeeks.org/"));
console.log(isValidURL(
"https://www.geeksforgeeks.org/community/"));
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(
"https://www.geeksforgeeks.org/"));
console.log(isValidURL(
"https://www.geeksforgeeks.org/community/"));
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);
// Additional checks, if necessary.
return true;
} catch (error) {
return false;
}
}
console.log(isValidURL(
"https://www.geeksforgeeks.org/"));
console.log(isValidURL(
"https://www.geeksforgeeks.org/community/"));
console.log(isValidURL("invalid-url"));
Approach 4: Using a Library (validator.js)
To check if a string contains a valid URL format using the validator.js library, first install the library using npm. Then, use the validator.isURL() method to validate the URL.
npm install validator
Example:
JavaScript
const validator = require('validator');
function isValidURL(str) {
return validator.isURL(str);
}
console.log(isValidURL("https://www.geeksforgeeks.org/")); // true
console.log(isValidURL("example")); // false
Output
true
false
Similar Reads
How to Extract URLs from a String in JavaScript ? In this article, we are given a string str which consists of a hyperlink or URL present in it. We need to extract the URL from the string using JavaScript. The URL must be complete and you need to print the entire URL. Example: Input :-str = "Platform for geeks: https://www.geeksforgeeks.org"Output
3 min read
JavaScript - Check if a String Contains Any Digit Characters Here are the various methods to check if a string contains any digital character1. Using Regular Expressions (RegExp)The most efficient and popular way to check if a string contains digits is by using a regular expression. The pattern \d matches any digit (0-9), and with the test() method, we can ea
4 min read
JavaScript - Check If a String Contains any Whitespace Characters Here are the various methods to check if a string contains any whitespace characters using JavaScript.1. Using Regular ExpressionsThe most common and effective way to check for whitespace is by using a regular expression. The \s pattern matches any whitespace character.JavaScriptconst s = "Hello Wor
3 min read
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and nu
4 min read
JavaScript Program to get Query String Values Getting query string values in JavaScript refers to extracting parameters from a URL after the "?" symbol. It allows developers to capture user input or state information passed through URLs for dynamic web content and processing within a web application. Table of Content Using URLSearchParamsUsing
2 min read
How to check a URL contains a hash or not using JavaScript ? In this article, the task is to check whether an URL contains or not. This can be done by using the Location hash property in JavaScript. It returns the string which represents the anchor part of a URL including the hash â#â sign. Syntax: window.location.hash Example: This example uses the hash prop
1 min read
How to Validate String Date Format in JavaScript ? Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation. There are many ways by which we can validate whether the D
5 min read
JavaScript - How to Check if a String Contains Double Quotes? Here are the different methods to check if a string contains double quotes.1. Using includes() MethodThe includes() method is the simplest way to check if a string contains a specific substring, including double quotes. This method returns true if the substring is found and false otherwise.JavaScrip
3 min read
JavaScript - Check if a String is a Valid IP Address Format An IP address is a unique identifier assigned to each device connected to a computer network that uses the Internet Protocol for communication. There are two common types of IP addresses: IPv4 and IPv6. In this article, weâll explore how to check if a string is a valid IP address format in JavaScrip
2 min read
JavaScript - How To Check if String Contains Only Digits? A string with only digits means it consists solely of numeric characters (0-9) and contains no other characters or symbols. Here are the different methods to check if the string contains only digits.1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string co
3 min read