1

From the MDN the split method separator is treated as a String or a RegExp. But 'asd'.split(['s']) correctly returns ['a', 'd'].

4
  • 3
    A lot of JS functions will try to coerce their argument(s) to the required type(s). ['s'].toString() gives 's'. Commented Jul 20, 2016 at 9:13
  • 1
    MDN says the separator is treated as a string. So this probably works because String(['s']) === 's'. Commented Jul 20, 2016 at 9:13
  • "If separator is a RegExp object (its [[Class]] is "RegExp"), let R = separator; otherwise let R = ToString(separator)." Commented Jul 20, 2016 at 9:15
  • the coercion rules as said by nnnnnn in fact "111a,s222".split(['a','s']) splits since ""+['a','s'] == 'a,s' Commented Jul 20, 2016 at 9:16

1 Answer 1

4

The specification for split includes the following step:

  1. Let R be ToString(separator).

So the array is coerced to a string, and the string representation of ['s'] is s.

It's worth noting that if you pass a regex to split, it doesn't get this far, as the regex object has an internal @@split method, which is used in step 3:

  1. If separator is neither undefined nor null, then

    a. Let splitter be GetMethod(separator, @@split).

    b. ReturnIfAbrupt(splitter).

    c. If splitter is not undefined , then

    i. Return Call(splitter, separator, «‍O, limit»).

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

1 Comment

Yes, you're right, I just checked it with an example console.log('as,df'.split(['s', 'd']) );

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.