skip to Main Content

I have a method that gets an array in the form of a string like "['123', '245345','2345']" I want to convert it to an array datatype. Here I want to remove the quotes and want the type to be an array. How can I do it easily in JS?

Input: "['123','234']" // string
output: ['123','234']  //array datatype

3

Answers


  1. You can try as follows

    const myString = "['123', '234']";
    
    
    const outputString = myString.replace(/^"(.*)"$/, "[$1]");
    
    console.log(outputString);
    

    Output:

    [‘123’, ‘234’]

    Login or Signup to reply.
  2. Like so:

    // Turn it into valid JSON (strings are doublequotes)
    const valueFormatted = "['123', '245345','2345']".replaceAll("'", `"`); 
    const result= JSON.parse(valueFormatted);
    console.log(result); // (3) [123, 245345, 2345]
    
    Login or Signup to reply.
  3. You could attempt to use eval()

    let x = eval("['123','234']")
    

    Will result in your expected output being stored in the local variable x

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search