skip to Main Content

I have the following code and I’ve got the id and name value in its own square bracket as shown below. How can I access the value of id and name?

let data = "[[id=3, name=BOX-3, description=test, comment=test, locationId=5, capacity=null]];"

        let id = data.match(/(?<=id=)d+(?=,)/g);
        let name = data.match(/(?<=name=)[w|-]*/g);

console.log(data);
console.log(id);
console.log(name);


console.log(id.match(/(?<=[)[^][]*(?=])/g) );

//console.log(idVal);

2

Answers


  1. You can destructure the result to get the match.

    let data = "[[id=3, name=BOX-3, description=test, comment=test, locationId=5, capacity=null]];"
    let [id] = data.match(/(?<=id=)d+(?=,)/g);
    let [name] = data.match(/(?<=name=)[w|-]*/g);
    
    console.log(id);
    console.log(name);
    Login or Signup to reply.
  2. let data = "[[id=3, name=BOX-3, description=test, comment=test, locationId=5, capacity=null]];"
    
    let id = data.match(/id=(d+)/);
    let name = data.match(/name=([w|-]+)/);
    
    if (id) {
      id = id[1]; // Extract the captured group value
    }
    
    if (name) {
      name = name[1]; // Extract the captured group value
    }
    
    console.log(data);
    console.log(id);
    console.log(name);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search