Olympus
Olympus

Reputation: 105

Why does the split() function in javascript work this way?

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 :)

Upvotes: 0

Views: 67

Answers (1)

mplungjan
mplungjan

Reputation: 177786

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.

Upvotes: 2

Related Questions