Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Regex .test() for whitespace [duplicate]

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?

like image 720
AfricanMatt Avatar asked May 26 '26 07:05

AfricanMatt


1 Answers

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  ');
like image 99
Pranav C Balan Avatar answered Jun 01 '26 10:06

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!