Ad

If Statement With .match(regex) In Javascript Not Picking Up Spaces

- 1 answer

Hi guys I'm trying to check if user input string contains a space. I'm using http://regexr.com/ to check if my regular expression is correct. FYI new to regex. Seems to be correct.

But it doesn't work, the value still gets returned even if there is a space. is there something wrong with my if statement or am I missing how regex works.

 var regex = /([ ])\w+/g;
 if (nameInput.match(regex)||realmInput.match(regex)) {
     alert('spaces not allowed');
 } else {
     //do something else 
 }

Thanks in Advance

Ad

Answer

This regex /([ ])\w+/g will match any string which contain a space followed by any number of "word characters". This won't catch, for example, a space at the end of the string, not followed by anything.

Try using /\s+/g instead. It will match any occurrence of at least one space (including tabs).

Update:

If you wish to match only a single space this will do the trick: / /g. There's no real need for the brackets and parenthesis, and since one space is enough even the g flag is kind of obsolete, it could have simply been / /.

Ad
source: stackoverflow.com
Ad