Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To validate alphabets and space string using regex, use /^[a-zA-Z]+(\s[a-zA-Z]+)?$/ it will handle all alphabates and space.

Let’s see short example of javascript regex for alphabets and space.

const regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
console.log(regex.test("hello "))

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

Here, I will show allow only alphabets and space character in javascript and typescript.

Javascript regex allow only alphabets and space character example

Here, we will create common validate function where we will validate param should alphabates and space.

function validate(param){
  const regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
  return regex.test(param);
}

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

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

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

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

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

Output

Typescript regex allow only alphabets and space and hyphen example

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

function validate(param: string){
  const regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
  return regex.test(param);
}

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

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

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

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

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

Output

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