0

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?

2 Answers 2

1

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'];
Sign up to request clarification or add additional context in comments.

2 Comments

why the forward slash at the end?
Just like quotes ' and " are string delimiters, forward slashes are regex delimiters.
1

You have to use backslash no quote when usign Regex:

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

1 Comment

why the forward slash at the end?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.