Search code examples
javascriptstringeval

Reading values with different datatypes inside a string in javascript


Assume i have a string var str = " 1, 'hello' " I'm trying to give a function the above values found in str but as integer and string- not as one string- for example myFunc(1,'hello') how can i achieve that i tried using eval(str), but I'm getting invalid token , How can i solve this?


Solution

  • The following should work with any number of arguments.

    function foo(num, str) {
      console.log(num, str);
    }
    
    const input = "1, 'hel,lo'";
    const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
    
    foo(...args);