Home > database >  split a string to array of arrays properly
split a string to array of arrays properly

Time:11-08

I have a string that looks like:

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

And I want to split it into an array of arrays of strings, I have tried to split this string as follows:

const msg_obj = new Array(JSON.parse(msg).split("["));
console.log(msg_obj);
for (let act_id in msg_obj) { 
    console.log(msg_obj[act_id]);
}

The problem is that I get unwanted characters/strings inside:

  1. Empty strings "".
  2. commas ,.
  3. square bracket ].

Can you please tell me if there is a better way to split this string into an array of arrays of strings without the unwanted output? thanks in advance.

CodePudding user response:

The problem is that your single quotes aren't valid JSON. You can easily get the result you want by replacing the quotes before parsing:

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

const msg_obj = JSON.parse(msg.trim().replace(new RegExp("'", "g"), "\""));

console.log(msg_obj);
for (let act_id in msg_obj) { 
    console.log(msg_obj[act_id]);
}

CodePudding user response:

Your const msg is not a valid json string. maybe you can parse this string by this codes :

const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"

msgArr = msg.split("], [").map(item => {  
    return item.trim().split(",").map(val => {
        return val.trim().replace(/\[|\'/g,'');  
    });  
})

example.png

  • Related