Spit a payload and get rid of the last bracket

Hi I am having a string

0.1.1.1|00:03:CD:01:6F:BA (Mobotix AG)
0.1.1.111|C2:4D:69:BB:65:A4 (American Power Conversion)
0.1.1.133|7C:87:AB:CD:EF:GH (Hewlett Packard)
............

Then I am trying to brin the strin into IP, MAC and hardware vendor.

let response = msg.payload.split('\n');
let found = []
let device
response.forEach ( line => {
    if ( line.indexOf('|') > -1 ){
        device = {
            IP : line.split('|')[0],
            MAC: line.split('|')[1].split(' ')[0],
            HW:  line.split('(')[1],
        }
        found.push ( device )
    }
})
msg.payload = found;
return msg;

the resault:

the IP, The MAC and Mobotix AG)
the IP, The MAC and American Power Conversion)
the IP, The MAC and Hewlett Packard)

BUT how can i get rid of the last closing bracket?

Hi, i would use line.substring() and line.findFrist and line.IndexOf() to search for | and the space

With slice you can remove the right characters

var mystring = "Hello world!";
msg.payload = mystring.slice(0,-1);

Will result in "Hello world" by removing 1 character from the right

THX
@ Christian-Me
i have not been able to get it to work properly in my existing function.
I have taken edje11 solution, because here it is always just a sign sign and it does not change.

Here is an alternative matching based on regular expression grouping

msg.payload = msg.payload.split('\n')

let results = []

msg.payload.forEach(line => {
    let group = line.match(/(.+)\|(.+)\s\((.*)\)/)
   if( group && group.length > 3)  results.push({ id: group[1], ip: group[2], name: group[3] })
});

msg.payload = results;
return msg;

Or split the lines using regex to

let lines = msg.payload.split('\n'); // you could also do ')\n'
msg.payload=[];
lines.forEach ( line => {
    let parts = line.split(/\||\(|\)/); // and here /\||\(/
    if ( parts.length >= 3 ){ 
        msg.payload.push({
            IP : parts[0].trim(),
            MAC: parts[1].trim(),
            HW:  parts[2].trim(),
        })
    }
})
return msg;

@UnborN the last match on line 4 of the string, will result in group being null, you need to add a conditional to lookout for a null match.

i didn't include the 4th line in the test as i considered that it was just there to imply that there were more lines
but yes, you are right, its good to check for null or length >= 3
(Edited the above post)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.