-1

I would like to do a regular expression that does not allow more than 1 consecutive spaces.

For example:

  • A Bb 7 is valid
  • AA O is not valid
  • 00 55 is valid
  • A b is not valid
Ivar
  • 6,138
  • 12
  • 49
  • 61
Yehuda Zadik
  • 99
  • 1
  • 3
  • 11
  • Check https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – James Nov 17 '22 at 15:58
  • Take a look at this https://stackoverflow.com/questions/21722081/regexp-to-allow-only-one-space-in-between-words . It's very similar with what you want – CW_ Nov 17 '22 at 15:58

3 Answers3

0

Here you can try this logic :

let str = "apple mango pine";

let result = str.match(/ {2,}/g);

if (result) {
  console.log("two consecutive spaces are not allowed");
} else console.log("valid");
Jerry
  • 1,005
  • 2
  • 13
0

Depending on your exact needs I can provide two versions:

This works with only the "space" character, but does not take other spacing characters from Unicode into account:

^[^ ]*(?: [^ ]+)* ?$

That takes the regex spacing characters into account, so also uses newlines, tabs etc. as "space":

^\S*(?:\s\S+)*\s?$

Both regular expressions match when they find a valid input.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
0

What makes you think you need a regular expression for this?

 if (string.includes('  '))
    alert('error!')
gog
  • 10,367
  • 2
  • 24
  • 38