Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Number Validation in JavaScript
Next article icon

JavaScript – Validate URL in JS

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We will explore different approaches to validating URLs in JavaScript. These approaches include using regular expressions (regex), the URL constructor, and various npm packages. let’s see one by one.

All valid URLs follow a particular pattern. They have three main parts, which are:

  • Protocol
  • Domain name (or IP address)
  • Port and path.

1. Using Regular Expression

To validate a URL in JavaScript using a regular expression (regex), we will use the following pattern to match the common URL format in the below example.

JavaScript
function isValid(url) {     const pattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-]*)*$/;     return pattern.test(url); }  //Driver Code Starts{ console.log(isValid("https://www.example.com")); console.log(isValid("http://example.com"));   console.log(isValid("www.example.com"));    console.log(isValid("invalid-url"));      //Driver Code Ends } 

Output
true true true false 

Explanation of the Regular Expression we used:

  • ^(https?:\/\/)?: Matches an optional http:// or https://.
  • ([\da-z.-]+): Matches the domain name (alphanumeric characters, dots, and hyphens).
  • \.: Matches the dot before the domain extension.
  • ([a-z.]{2,6}): Matches the domain extension (For ex., .com, .org).
  • ([\/\w .-]*)*\/?: Matches the optional path, query strings, or fragments.

2. Using URL Object

The URL object in JavaScript provides a built-in way to parse and validate URLs. It is robust, handles complex cases, and doesn’t require writing or maintaining custom regular expressions.

JavaScript
function isValid(url) {     try {         new URL(url);         return true;     } catch (e) {         return false;     } }   //Driver Code Starts{ console.log(isValid("https://www.example.com"));  console.log(isValid("http://example.com"));      console.log(isValid("www.example.com"));       console.log(isValid("invalid-url"));          //Driver Code Ends } 

Output
true true false false 

3. Using npm Packages

There are two npm packages is-url and is-url-http to validate URL. Install the packages with the following command:

npm install is-url
npm install is-url-http

Using is-url npm Packages

JavaScript
import isUrl from 'is-url'; console.log(isUrl("https://www.example.com"));  console.log(isUrl("http://example.com"));    console.log(isUrl("www.example.com"));        console.log(isUrl("invalid-url"));            

Output

true
true
false
false

4. Using is-url-http npm Packages

JavaScript
import isUrlHttp from 'is-url-http'; console.log(isUrlHttp("https://www.example.com")); console.log(isUrlHttp("http://example.com"));    console.log(isUrlHttp("www.example.com"));      console.log(isUrlHttp("invalid-url")); 			  

Output

true
true
false
false


Next Article
Number Validation in JavaScript

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-RegExp

Similar Reads

  • JavaScript - Validate URL in JS
    We will explore different approaches to validating URLs in JavaScript. These approaches include using regular expressions (regex), the URL constructor, and various npm packages. let's see one by one. All valid URLs follow a particular pattern. They have three main parts, which are: ProtocolDomain na
    2 min read
  • Number Validation in JavaScript
    Here are the various methods to validate numbers in JavaScript 1. Check if a Value is a NumberUse typeof and isNaN() to determine if a value is a valid number. [GFGTABS] JavaScript const isNum = n => typeof n === 'number' && !isNaN(n); console.log(isNum(42)); console.log(isNum(
    3 min read
  • JavaScript regex - Validate Credit Card in JS
    To validate a credit card number in JavaScript we will use regular expression combined with Luhn's algorithm. Appling Luhn's algorithm to perform a checksum validation for added security Luhn algorithm:It first sanitizes the input by removing any non-digit characters (e.g., spaces).It then processes
    3 min read
  • How to Validate XML in JavaScript ?
    Validation of XML is important for ensuring data integrity and adherence to XML standards in JavaScript. There are various approaches available in JavaScript using which validation of the XML can be done which are described as follows: Table of Content Using DOM ParserUsing Tag MatchingUsing DOM Par
    2 min read
  • How to validate URL in ReactJS?
    URL (Uniform Resource Locator) is a reference/address to a resource on the Internet. For example, www.geeksforgeeks.com is a URL. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application. Creating React App
    2 min read
  • JavaScript Form Validation
    JavaScript form validation checks user input before submitting the form to ensure it's correct. It helps catch errors and improves the user experience. What we are going to CreateIn this article, we will guide you through creating a form validation application. This application will validate essenti
    11 min read
  • How to Validate Number String in JavaScript ?
    Validating a number string in JavaScript involves ensuring that a given string represents a valid number. This typically includes checking for digits, optional signs (+/-), decimal points, and possibly exponent notation (e.g., "1.23e4"). We will use various methods to validate number strings in Java
    2 min read
  • How to Validate Checkbox in JavaScript?
    Validation of checkboxes is important to make sure that users select the required options, enhancing data accuracy and user experience. Table of Content Using a LoopUsing FormData ObjectUsing a LoopIn this approach, we are using a loop to iterate through each checkbox in the form. We check if any ch
    2 min read
  • Validate a password using HTML and JavaScript
    Validating a password using HTML and JavaScript involves ensuring that user-entered passwords meet certain criteria, such as length, complexity, or character types (e.g., uppercase, lowercase, numbers, and symbols). This process enhances security by enforcing strong password requirements before form
    2 min read
  • How to Validate Decimal Numbers in JavaScript ?
    Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format. We can use the regular expression to Validate Decimal N
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences