0

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? :/

6
  • 5
    "limit: Optional. Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, but it truncates the returned array to at most limit elements." -- MDN Commented Jan 29, 2015 at 22:43
  • wow... you set up, that you want only 2 element and complaining that you get only 2... nice!!! Commented Jan 29, 2015 at 22:44
  • To do a single split, you might be able to use .split(/\/\/) instead. Unless marked as global (/g), a regex will only match once. Commented Jan 29, 2015 at 22:44
  • weird, I didn't expect that. In PHP explode doesn't work this way :| Commented Jan 29, 2015 at 22:45
  • you set a limit=2 on the split function Commented Jan 29, 2015 at 22:45

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This code shows what the OP actually wanted and expected from split, it answers the question indirectly by saying that you need more logic to make this work. However it doesn't fully answer why the OP's approach is flawed.
1

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('/'));

Comments

1

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

Comments

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.