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.
function isValidURL(url) {
try {
const urlObject = new URL(url);
// Additional checks, if necessary.
return true;
} catch (error) {
return false;
}
}
console.log(isValidURL(
"https://www.w3wiki.org/"));
console.log(isValidURL(
"https://ide.w3wiki.org/online-html-editor"));
console.log(isValidURL("invalid-url"));
Output
true true false
How to Check if a String Contains a Valid URL Format in JavaScript ?
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.
Table of Content
- Using Regular Expressions
- Using URL Constructor
- Using the URL Object Available in Modern Browsers
- Using a Library (validator.js)
We will explore all the above methods along with their basic implementation with the help of examples.