Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To allow only alphanumeric and hyphen, use this regex /^[a-z\d\-\s]+$/i it will return true if value contain only alphanumeric and hyphen.

Let’s see short example of javascript regex allow alphanumeric and hyphen.

const regex = /^[a-z\d\-\s]+$/i;
console.log(regex.test("hello-8943"))

Today, I’m going to show you How do I check value contain only alphanumeric and hyphen 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 allow only alphanumeric and hyphen in javascript using regex?

If you want to also allow underscore and hyphen use this regex /^[a-z\d\-_\s]+$/i.

Here, I will show allow only alphanumeric and hyphen in javascript and typescript.

Javascript regex allow only alphanumeric and hyphen example

Here, we will create common validate function where we will validate param should numbers and dots.

function validate(param){
  const regex = /^[a-z\d\-]+$/i;
  return regex.test(param);
}

// validate empty
console.log(validate(""))
// false

// validate string
console.log(validate("INFINIT"))
// true

// validate number
console.log(validate("8954"))
// true

// validate words with space
console.log(validate("infinit bility"))
// false

// validate words with hyphen
console.log(validate("infinit-bility"))
// true

Output

Typescript regex allow only alphanumeric and hyphen example

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

function validate(param: string){
  const regex = /^[a-z\d\-]+$/i;
  return regex.test(param);
}

// validate empty
console.log(validate(""))
// false

// validate string
console.log(validate("INFINIT"))
// true

// validate number
console.log(validate("8954"))
// true

// validate words with space
console.log(validate("infinit bility"))
// false

// validate words with hyphen
console.log(validate("infinit-bility"))
// true

Output

I hope it helps you, All the best đź‘Ť.