0

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

2
  • 2
    What exact input do you have for nameInput and realmInput that doesn't have the expected result? Commented Jan 22, 2016 at 0:40
  • jsfiddle.net/0vx058bk Commented Jan 22, 2016 at 0:51

2 Answers 2

1

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 / /.

Sign up to request clarification or add additional context in comments.

1 Comment

I would also offer /[ ]/g if you do not want to match other whitespace characters.
0

Your current regex doesn't match 'abc '(a word with space character at the end) . If you want to make sure, you can trim you input before check :).

You can check here https://regex101.com/

The right regex for matching only white space is

/([ ])/g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.