Javascript regex URL domain

A URL – or Uniform Resource Locator – is text used to identify resources like web pages, images, and videos on the internet.

We commonly refer to URLs as website addresses, and they're used for file transfer, emails, and other applications.

URLs consist of multiple parts – protocol, domain name, and so on – that tell the browser how and where to retrieve the resource.

In JavaScript, you may need to use a URL in the anchor tags or buttons to link the user to another webpage. This URL string must be verified to make sure it's a valid URL in such situations.

This tutorial will teach you some ways to check if a JavaScript string is a valid URL.

To learn how to get the current URL in JavaScript, you can read this article on How to Get the Current URL in JavaScript.

How to Check if a String is a Valid URL Using Regex

Regular expressions (regex) are patterns that match character combinations in a JavaScript string. In JavaScript, regular expressions are also known as objects that provide different methods to perform various operations.

You can construct a regular expression in two ways:

  • Using regular expression literals
  • Using regular expression constructors

Note: It is appropriate to use the regular expression method when you just want to check if a string is a valid URL and don't want any other additional objects created.

Let's learn how these two methods work.

How to use regular expression literals

In a regular expression literal, the pattern is enclosed between the slashes, as you'll see below.

The pattern includes the validation of parts needed in the

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3. For example, a protocol,
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
4, a
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
5, and so on.

const urlPattern = /(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;

How to use a regular expression constructor

To create a regular expression using the construction method, use the

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
6 constructor and pass the pattern as a parameter.

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');

To demonstrate how to validate if a string is a

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3, let's create a method that will validate a JavaScript
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
8 using the regular expression constructor and return
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
9 or
	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
0 based on the matched pattern.

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}

How to use regex to validate a URL string

The code below demonstrates how to validate different URL strings using the above method:

	var url = "invalidURL";
	console.log(isValidUrl(url));      //false
	 
	var url = "htt//jsowl";            //false
	console.log(isValidUrl(url));
	
    var url = "www.jsowl.com";         //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com"; //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
    console.log(isValidUrl(url));      //true

How to Check if a String is a Valid URL using URL Constructor

You can use the URLConstructor to check if a string is a valid URL.

URLConstructor (

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
1) returns a newly created URL object defined by the URL parameters.

A JavaScript

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
2 exception is thrown if the given URL is not valid.

Note: It is appropriate to use this method when you want to construct a URL object in your program for further uses.

URL Constructor Syntax

The following syntax explains how to create a URL Object with a JavaScript String.

new URL(url);
new URL(url, base);

Where,

  • 	const isValidUrl = urlString=> {
    	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
    	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
    	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
    	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
    	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
    	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    	  return !!urlPattern.test(urlString);
    	}
    
    3 is a string or any object with a stringifier that represents an absolute or relative URL. If URL is an absolute URL, base shall be ignored. If URL is a relative URL, base is required.
  • 	const isValidUrl = urlString=> {
    	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
    	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
    	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
    	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
    	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
    	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    	  return !!urlPattern.test(urlString);
    	}
    
    4 (optional) is a string representing the base URL. It must be passed when the URL is relative. Defaults to undefined when ignored.

Example of URL Constructor method

To demonstrate how the URL constructor method works, let's create a lambda function in JavaScript to construct a new URL with the passed string.

  • If the string is a valid URL, a URL object is created, and
    	const isValidUrl = urlString=> {
    	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
    	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
    	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
    	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
    	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
    	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    	  return !!urlPattern.test(urlString);
    	}
    
    5 is returned
  • If the String is not a valid URL, a
    	const isValidUrl = urlString=> {
    	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
    	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
    	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
    	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
    	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
    	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    	  return !!urlPattern.test(urlString);
    	}
    
    6 exception is thrown, and
    	const isValidUrl = urlString=> {
    	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
    	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
    	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
    	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
    	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
    	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
    	  return !!urlPattern.test(urlString);
    	}
    
    7 is returned
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }

How to use the const isValidUrl = urlString=> { var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator return !!urlPattern.test(urlString); } 8 method

Let's invoke the

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
8 method for different string types and see the results.

  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true

In the first three cases, you can see that an invalid URL string is passed. As a result, URL object creation fails with a

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
2 and
	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
7 is returned.

In the last two cases, valid URL string is passed. So a

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3 object is created successfully, and
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
9 is returned, confirming the proper URL.

Let's see one more example to validate a specific URL part.

In this example, you are validating a specific protocol in the URL. The URL must contain the

	var url = "invalidURL";
	console.log(isValidUrl(url));      //false
	 
	var url = "htt//jsowl";            //false
	console.log(isValidUrl(url));
	
    var url = "www.jsowl.com";         //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com"; //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
    console.log(isValidUrl(url));      //true
4 or
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
4 protocol.

	const isValidUrl = urlString=> {
		let url;
		try { 
	      	url =new URL(urlString); 
	    }
	    catch(e){ 
	      return false; 
	    }
	    return url.protocol === "http:" || url.protocol === "https:";
	}

Example of how to validate part of a URL

Let's invoke the

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
8 method for different string types and protocols and see the results.

var url = "tcp://www.jsowl.com";
console.log(isValidUrl(url));      //false

var url = "https://www.jsowl.com";
console.log(isValidUrl(url));      //true

In the first case, the URL string (tcp://www.jsowl.com) is valid, but it doesn't contain a specific protocol (

	var url = "invalidURL";
	console.log(isValidUrl(url));      //false
	 
	var url = "htt//jsowl";            //false
	console.log(isValidUrl(url));
	
    var url = "www.jsowl.com";         //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com"; //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
    console.log(isValidUrl(url));      //true
7/
	var url = "invalidURL";
	console.log(isValidUrl(url));      //false
	 
	var url = "htt//jsowl";            //false
	console.log(isValidUrl(url));
	
    var url = "www.jsowl.com";         //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com"; //true
    console.log(isValidUrl(url));
    
    var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
    console.log(isValidUrl(url));      //true
8). So it returns false.

In the second case, the URL string https://www.jsowl.com is valid and contains the specific protocol. So it returns true.

How to Check if a String is a Valid URL Using an Input Element

HTML supports an input element with type

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
3,  specifically for representing URL values.

The

new URL(url);
new URL(url, base);
0 element's
new URL(url);
new URL(url, base);
1 attribute containing the string is automatically validated by matching the URL syntax (either has an empty or properly formed URL) before the form can be submitted.

new URL(url);
new URL(url, base);
2 method is used to check if a string in  
new URL(url);
new URL(url, base);
0 element’s value attribute is
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3. The
new URL(url);
new URL(url, base);
5 method returns
	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
5 if the value is a proper URL and
	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
7 if the input is not a proper URL.

Let's create a method which creates an input element type

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3 and validates the input using the
new URL(url);
new URL(url, base);
9 method.

    const isValidUrl = urlString =>{
      var inputElement = document.createElement('input');
      inputElement.type = 'url';
      inputElement.value = urlString;

      if (!inputElement.checkValidity()) {
        return false;
      } else {
        return true;
      }
    } 

Now let's use this method and validate different strings to see if they are valid URLs.

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
0

This is how you can use the input type method to check if a string is a valid URL.

How to Check if a String is a Valid URL Using the Anchor Tag Method

This section teaches you how to use the HTMLAnchorElement to check whether a JavaScript string is a URL.

Note: It is appropriate to use this method when you want to assign a URL to the

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
0 tag of your webpage and ensure that the URL string is valid and gets assigned to the
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
0 tag properly.

The

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
2 interface represents hyperlink elements. It provides special properties and methods for manipulating the layout and presentation of such elements. It is also called an anchor tag.

You can assign a URL to an anchor tag using the

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
3 attribute. While assigning,

  • If a valid URL string is passed, it is assigned to the anchor tag
  • If an invalid URL is passed, the current browser location is assigned to the anchor tag
  • By default, the anchor tag will have an empty URL (“”)

Once the URL is assigned, you can extract a specific part of the URL using the attributes explained below.

HTMLAnchorElement atributeusage
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
4a string representing hostname and port
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
5a string representing hostname
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
3a string containing a valid URL
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
7returns a string containing the origin, its schema, domain name and port
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
8a string representing the port if specified
const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
9a string representing the protocol including the trailing('
  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true
0')
  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true
1a string containing the path URL from initial (/) and not including the query string

Now, let's see how to check if the assigned string was a proper URL.

If it was a proper URL, it would be assigned to the anchor tag. Else, the current browser location will be assigned to the anchor tag.

So to check if it was a proper URL, you can check if the anchor tag’s

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
4 is NOT equal to the current location using the statement
  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true
3.

Let's look at the code.

We create a lambda function and assign it to the constant

  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true
4 in the code below.

The function creates an anchor tag element and assigns the URL string to the anchor tag. After that, it checks if the

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
4 attribute of the element is
  var url = "invalidURL";
  console.log(isValidUrl(url));     //false
  
  var url = "htt//jsowl";
  console.log(isValidUrl(url));     //false
  
  var url = "www.jsowl.com";
  console.log(isValidUrl(url));     //false
  
  var url = "tcp://www.jsowl.com";
  console.log(isValidUrl(url));     //true
  
  var url = "https://www.jsowl.com/remove-an-item-from-an-array-in-javascript/";
  console.log(isValidUrl(url));     //true
6 or not defined.

If it is not null, it checks whether the

const isValidUrl = urlString=> {
      try { 
      	return Boolean(new URL(urlString)); 
      }
      catch(e){ 
      	return false; 
      }
  }
4 attribute is NOT equal to the current browser URL and returns
const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
9 when it is not equal.

This is because if the passed URL was valid, then the anchor tag will have the URL value. But if the passed URL was invalid, the anchor tag will have the current browser location. In this case, the lambda function returns

	const isValidUrl = urlString=> {
	  	var urlPattern = new RegExp('^(https?:\\/\\/)?'+ // validate protocol
	    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // validate domain name
	    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // validate OR ip (v4) address
	    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // validate port and path
	    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // validate query string
	    '(\\#[-a-z\\d_]*)?$','i'); // validate fragment locator
	  return !!urlPattern.test(urlString);
	}
0.

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
1

The below code snippets invoke the lambda function

	const isValidUrl = urlString=> {
		let url;
		try { 
	      	url =new URL(urlString); 
	    }
	    catch(e){ 
	      return false; 
	    }
	    return url.protocol === "http:" || url.protocol === "https:";
	}
0 with different inputs and print the output accordingly in the console.

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
2

This tutorial is available in this JSFiddle.

Conclusion

In this article, you've learned how to check if a JavaScript string is a

const urlPattern = new RegExp('(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?');
3 using different methods and when it is appropriate to use each method.

If you liked this article, feel free to share it.

You can check out my other tutorials on my blog, JS Owl.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


Javascript regex URL domain
Vikram Aruchamy

AWS Solutions Architect and Full-time Technical writer at stackvidhya.com and jsowl.com.


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How to get the domain name from URL in JavaScript?

Follow the syntax below to get the hostname. var url = new URL("www.sample.com"); var hostname = url. hostname; Here we access the hostname property from the URL directly.

How do I extract a domain name from a URL?

In the first cell of the "Domain" column (B2), enter the formula to extract a domain name:.
Extract the domain with www. if it is present in a URL: =MID(A2,FIND(":",A2,4)+3,FIND("/",A2,9)-FIND(":",A2,4)-3).
Omit www. and get a pure domain name: =IF(ISERROR(FIND("//www.",.

Can I use regex in URL?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.

How to split domain name in JavaScript?

var newURL="http://www.example.com/index.html/homePage/aboutus/"; console. log(newURL); var splitURL=newURL. toString(). split("/"); console.