0

I'm trying to understand how the split() function works in the below scenario:

'aaa'.split('a')

The output I'm getting is:

[ '', '', '', '' ]

Why do we get an array of size 4 with an empty string in each slot?

Thanks :)

asked Mar 19, 2021 at 7:15
1
  • Just like the empty set is part of every set, between every character there is an empty string. Commented Mar 19, 2021 at 8:17

1 Answer 1

2

Because you get

'aaa'.split('a')
""a""a""a""

but the pattern you split on is not retained

If you want to split a string into characters, use the empty string

'aaa'.split('')

or spread:

[...'aaa']

Split

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

answered Mar 19, 2021 at 7:17
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.