Q:

splitting string as per regex in typescript is not working as expected for multiple space

In typescript I want to divide a name as per space. So, I used something like this
const splitted = name.split(' ');

It is working as expected, but if wrongly someone gave more than one space. So, i tried to handle multiple space to split. Like this,
const splitted = name.split('\\s+');

But, it is taking the whole string as 1 And, length of splitted varabel it is showing 1
It is working in java
Any explanation?

A:

If you want to split along a regular expression, you need to pass an actual regular expression to split:
const splitted = name.split(/\s+/);

Your current code will split along a literal backslash, followed by a literal s and +, eg:
const name = 'foo\\s+bar';
const splitted = name.split('\\s+');
// splitted: ['foo', 'bar'];

