I would like to do a regular expression that does not allow more than 1 consecutive spaces.
For example:
A Bb 7
is validAA O
is not valid00 55
is validA b
is not valid
CodePudding user response:
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");
CodePudding user response:
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.
CodePudding user response:
What makes you think you need a regular expression for this?
if (string.includes(' '))
alert('error!')