3

Strange regex result when looking for any white space characters

new RegExp('^[^\s]+$').test('aaa');
=> true

That's expected, but then...

new RegExp('^[^\s]+$').test('aaa  ');
=> true

How does that return true?

AfricanMatt
  • 145
  • 1
  • 9

1 Answers1

5

You need to escape \ in the string by \\. Otherwise, the generated regex would be /^[^s]+$/, which matches anything other than a string includes s.

new RegExp('^[^\\s]+$').test('aaa  ');

Or you can use \S for matching anything other than whitespace.

new RegExp('^\\S+$').test('aaa  ');

It would be better to use regex directly instead of parsing a regex string pattern.

/^[^\s]+$/.test('aaa  ');

// or

/^\S+$/.test('aaa  ');
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188