Satish Patro
Satish Patro

Reputation: 4404

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?

Upvotes: 0

Views: 200

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You have to use backslash no quote when usign Regex:

const splitted = name.split(/\s+/g);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370929

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'];

Upvotes: 1

Related Questions