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.
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);
Similar to user3146092's answer, this one will not rely on your function having to parseInt
.
someMagic.apply(this, '1,2'.split(',').map(function(n) { return parseInt(n, 10); }));
You can create an array of numbers and pass them as your arguments, that in fact, is the best way to do it in JavaScript.
var nums = "1,2,3"
.split(",")
.map(function (num) { return parseInt(num, 10) });
Now you can pass nums
as your arguments.