Home > Mobile >  How to Allow multiple spaces in between the text using regex
How to Allow multiple spaces in between the text using regex

Time:12-13

I have the following regex:

^([A-Za-z0-9\._-]  ) [A-Za-z0-9\._-] $|^[A-Za-z0-9\._-] $

This allows alphanumeric characters, dots, underscores, and hyphens. I want the regex also to allow multiple spaces in between. How do I do this?

CodePudding user response:

use

  1. \s
  2. [ ]
  3. [ ]{2,3} if you need exclude 1 space
string = string.match(^([A-Za-z0-9\._-]  ) \s [A-Za-z0-9\._-] $|^[A-Za-z0-9\._-] $);

CodePudding user response:

If I understand correctly you want:

  • to allow only alphanumeric chars, dots and hyphens in words
  • 1 spaces are allowed between words, but not leading and trailing spaces

Here is a solution that allows multiple spaces ( instead of ), and simplifies the word regex to [\w\.-] from [A-Za-z0-9\._-] since \w contains [A-Za-z0-9_] :

[
  'all-allowed.chars',
  'one space',
  'two  space',
  ' leading space',
  'trailing space ',
  'off-limits:!@#$%^&*()_ '
].forEach(str => {
  let result = /^([\w\.-]   ) [\w\.-] $|^[\w\.-] $/.test(str);
  console.log(str, ' => ', result);
});
 

Output:

all-allowed.chars  =>  true
one space  =>  true
two  space  =>  true
 leading space  =>  false
trailing space   =>  false
off-limits:!@#$%^&*()_   =>  false
  • Related