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.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.

Similar Reads

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....

Approach 2: Using URL Constructor

URL constructor in JavaScript creates a URL object, checks if given string is a valid URL; throws error otherwise....

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....

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....

Contact Us