0

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.

Jazzy
  • 6,029
  • 11
  • 50
  • 74
  • 1
    can you provide more example ? – Anik Islam Abhi Nov 08 '15 at 03:57
  • Ideally, I want to call some `function(1,2)` by converting `"1,2"` from a string into args. – Jazzy Nov 08 '15 at 03:59
  • The exact thing you are trying to achieve is impossible. Think about it: `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 use `eval`, I guess that's not what you want to use. – Felix Kling Nov 08 '15 at 04:06
  • @FelixKling I actually tried and it returns `2`. `eval` would work for this but it's not working as expected. – Jazzy Nov 08 '15 at 04:15

6 Answers6

1

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

Dhiraj
  • 33,140
  • 10
  • 61
  • 78
1
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.

Community
  • 1
  • 1
lvl2pillow
  • 21
  • 1
0

Using split is the answer.

var string = "1,2";
var splitString = string.split(","); //use , as an parameter to split

http://www.w3schools.com/jsref/jsref_split.asp

Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
0
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);
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

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); }));
kmiyashiro
  • 2,249
  • 14
  • 15
0

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.

David Gomez
  • 2,762
  • 2
  • 18
  • 28