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?
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?
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 ');