0

I have this Array ["2.900000F02A_1313_01","2.600000F02A_1315_03","2.900000F02A_1354_01"]

And I want to split it like this:

[
    {"name":"F02A_1313_01", "Voltage":"2.900000"}, 
    {"name":"F02A_1315_03", "Voltage":"2.600000"},
    {"name":"F02A_1354_01", "Voltage":"2.900000"}
]

This is my Code that doesn't work:

for (var i in msg.strg) {
     array.push(i.split(/[a-zA-Z].*/g));
 }

Does somebody know how I can do this?

1
  • 1
    What is the general rule to know where to split? First non-numeric character? Commented Mar 3, 2021 at 9:52

2 Answers 2

5

You could split with a group.

const
    data = ["2.900000F02A_1313_01", "2.600000F02A_1315_03", "2.900000F02A_1354_01"],
    result = data.map(string => {
        const [Voltage, name] = string.split(/([a-z].*$)/i);
        return { name, Voltage };
    });

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

You could also make the match a bit more specific, matching the digits for Voltage (\d+(?:\.\d+)?) in group 1 , and a case insensitive char a-z followed by word characters (F\w+) in group 2.

const arr = ["2.900000F02A_1313_01","2.600000F02A_1315_03","2.900000F02A_1354_01"];
const result = arr.map(s => {
    const m = s.match(/^(\d+(?:\.\d+)?)([a-z]\w+)$/i);
    return {name: m[2], Voltage: m[1]}
});
console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.