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

2
  • Get rid of the []: try 'what a mess'.split(/\s+/) Commented Feb 12, 2018 at 22:22
  • 'what a mess'.split(/\s+/) Commented Feb 12, 2018 at 22:23

1 Answer 1

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]/));

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

1 Comment

Why the DV? This seems perfectly cogent.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.