0

i try to split words in a String with string.split() and use regExp as separator, it also splits with s.

'what a mess'.split(RegExp('[\s]')); // -> ["what", "a", "me", "", ""]

how can i say that only the whitespace is a separator? thanks you for the help

1 Answers1

1

When you give a string to the RegExp constructor, any backslashes are interpreted as escaping something in the string itself, and they don't make it into the regex. You can either double escape your backslashes, or use a regex literal:

console.log('what a mess'.split(RegExp('[\s]')));

console.log('what a mess'.split(RegExp('[\\s]')));
console.log('what a mess'.split(/[\s]/));
CRice
  • 29,968
  • 4
  • 57
  • 70