thelolcat
thelolcat

Reputation: 11545

Split not working correctly in javascript

Check this out

alert("wtf/http://google.com".split('/', 2));

the resulted array contains 2 elements: wtf, http:.

Shouldn't it have wtf and the rest of the string? :/

Upvotes: 0

Views: 686

Answers (3)

wnbates
wnbates

Reputation: 753

The 2nd value passed to the split function limits your results but not where the array is split. To clarify the split separates it into 4 sections first then only returns the first two.

If you're trying to split out the wtf and the url try the following:

alert("wtf/http://google.com".split(/\/(.+)/,2))

Upvotes: 2

flareartist
flareartist

Reputation: 814

It's because you're splitting on the '/' and there are 4 slashes. It's just splitting up to the next '/' it finds, which would be '//google.com'.

If you do:

alert("wtf/http://google.com".split('/', 4));

you'll get all the pieces, just not separated into 2 chunks the way you want

Upvotes: 1

larsAnders
larsAnders

Reputation: 3813

The last integer in the function call specifies that split will return only two pieces. You just need to increase that number to 4, or remove it entirely.

alert("wtf/http://google.com".split('/'));

Upvotes: 1

Related Questions