Hi Friends 👋,

Welcome To Infinitbility! ❤️

To validate domain name string using regex, use /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/ it will handle domain name.

Let’s see short example of javascript regex for domain name.

const regex = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/;
console.log(regex.test("infinitbility.com"))

Today, I’m going to show you How do I check value contain domain name in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you check domain name in javascript using regex?

Here, I will show validate domain name in javascript and typescript.

Javascript regex for domain name example

Here, we will create common validate function where we will validate param should domain name.

function validate(param){
  const regex = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/;
  return regex.test(param);
}

// validate http domain
console.log(validate("http://infinitbility.com"))
// true

// validate https domain
console.log(validate("https://infinitbility.com"))
// true

// validate sub domain
console.log(validate("https://editor.infinitbility.com"))
// true

// validate country based domain
console.log(validate("https://infinitbility.co.in"))
// true

// validate domain with www
console.log(validate("https://www.infinitbility.com"))
// true

// validate domain with url
console.log(validate("https://infinitbility.com/sub-url"))
// true

Output

Typescript regex for domain name example

Same like javascript, we will create a function and call it with diffrent parameters.

function validate(param: string){
  const regex = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/;
  return regex.test(param);
}

// validate http domain
console.log(validate("http://infinitbility.com"))
// true

// validate https domain
console.log(validate("https://infinitbility.com"))
// true

// validate sub domain
console.log(validate("https://editor.infinitbility.com"))
// true

// validate country based domain
console.log(validate("https://infinitbility.co.in"))
// true

// validate domain with www
console.log(validate("https://www.infinitbility.com"))
// true

// validate domain with url
console.log(validate("https://infinitbility.com/sub-url"))
// true

Output

I hope it helps you, All the best 👍.