1

I have some logic that requires at some point running of native JavaScript functions and passing "dynamic" arguments to those functions. For example, I need to call the split function on an array of arguments defined as ["i want to split this", " " ]

What i am trying so far is the following:

String.prototype.split.call("i want to split this", " ") works fine, but since i have my arguments as an array , then i need to use apply. However:

String.prototype.split.apply(null, ["i want to split this", " " ])

will not work and i will get Uncaught TypeError: String.prototype.split called on null or undefined

Something that works is using the call with spread syntax .. so that:

String.prototype.split.call(...["i want to split this", " " ])

but the problem is that my Node.js version does not support spread syntax yet.

Would appreciate any help on this.

4
  • Why couldn't you reverse your thinking an make your own split() function that accepts either a single string or an array and splits accordingly? Commented Feb 1, 2017 at 18:31
  • @ScottMarcus the issue here is that i might be calling other native functions like split .. split here is just an example .. but basically it can be any native javascript function Commented Feb 1, 2017 at 18:32
  • How are you determining what string gets split? Or on which object a native function may be called. It sounds like you're abstracting too much, IMO. Commented Feb 1, 2017 at 18:33
  • @MikeMcCaughan to give you a bit of background, these functions are defined as strings inside of a mapping file. They will picked up by a processing function and executed, so basically who writes the mapping has already working knowledge of how arguments should be passed to the function. I hope this answered your question Commented Feb 1, 2017 at 18:35

1 Answer 1

2

You are looking for

String.prototype.split.apply("i want to split this", [" "])

which is the equivalent to

String.prototype.split.call("i want to split this", " ")

If you have an array to work with instead of context and arguments separately, you can do

var arr = ["i want to split this", " "];
String.prototype.split.apply(arr[0], arr.slice(1))

or (if you don't care about mutating):

String.prototype.split.apply(arr.shift(), arr)
Sign up to request clarification or add additional context in comments.

3 Comments

@Redu That it doesn't work with arbitrarily many arguments. Sure, if a.length is guaranteed to be 2, then that's what you should be using.
Well, calling split with more that one string argument doesn't do much, does it?
Sure, but OP said "i might be calling other native functions like split" so I guessed they might be chosen dynamically.

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.