Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To allow space between words, use this regex /^\w+( \w+)*$/ it will return true if value contain space between words and false if space have in the left or right side and it’s also return false double space between words.

Let’s see short example to use regex in javascript

const regex = /^\w+( \w+)*$/;
console.log(regex.test("hello 8943"))

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

Here, I will show allow space between words in javascript and typescript.

Javascript regex allow space between words example

Here, we will create common validate function where we will validate param have space between words or not.

function validate(param){
  const regex = /^\w+( \w+)*$/;
  return regex.test(param);
}

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

// validate number
console.log(validate(39.89))
// false

// validate string with both side space
console.log(validate(" infinitbility "))
// false

// validate string with double space
console.log(validate("infinitbility  aguidehub"))
// false

// validate string space between two words
console.log(validate("infinitbility aguidehub"))
// true

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

Output

Typescript regex allow space between words example

Here, we will create common validate function where we will validate param have space between words or not.

function validate(param: string){
  const regex = /^\w+( \w+)*$/;
  return regex.test(param);
}

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

// validate string with both side space
console.log(validate(" infinitbility "))
// false

// validate string with double space
console.log(validate("infinitbility  aguidehub"))
// false

// validate string space between two words
console.log(validate("infinitbility aguidehub"))
// true

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

Output

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