Is there a way to convert "1,2" into 1,2 using native JS without some sort of wrapper?
"1,2".someMagic() \\ 1,2
Ultimately, I want to pass this as arguments to a function.
Firstly, no there is no way to convert "1,2" to literally 1,2. Because it is invalid type. 1,2 is better represented as an array
You can use .apply like below to send 1,2 as parameters (array format) to the function someMagic
someMagic.apply(context, [1,2]);
Apply would call someMagic and send 1,2 as parameters
function doSomething(param1, param2) {
return parseInt(param1)+parseInt(param2);
};
doSomething.apply(this, "1,2".split(","));
// returns 3
Perhaps this thread Converting an array to a function arguments list may be of interest to you.
Using split is the answer.
var string = "1,2";
var splitString = string.split(","); //use , as an parameter to split
var str = "1,2,3,4,5,6";
var arr=[];
function process(str){
// split the string into tokens
arr = str.split(",");
// go through each array element
arr.forEach(function(val,index,ar){
// convert each element into integer
var temp = parseInt(val);
// repopulate array
arr[index] = temp;
});
}
process(str);
console.log(arr);
function(1,2)by converting"1,2"from a string into args.func(1, 2)is parsed as a function call with two arguments. I.e. the engine already knows, before executing the code what, this is, just by parsing it. OTOH"1,2"is a string literal. You want to transform it to something else at runtime, i.e. after all the code has been parsed. You want to convert a runtime value to a syntax construct. Syntax cannot be changed or created at runtime. The only way to do that is to useeval, I guess that's not what you want to use.2.evalwould work for this but it's not working as expected.