Home > Software engineering >  map a string to an object using regex
map a string to an object using regex

Time:03-24

for some translations need, I need to replace a string having three brackets like

hello {{{'something'}}} world {{{'something else'}}} ... 

with a string containing two brackets and the values

{ 
  value: "hello {{1}} world {{2}}...",
  params: {1: 'something', 2: 'something else', ...}
}

I started with this codepen :

let brutto = "hello {{{'something'}}}} world {{{'something else'}}} ... ";
let regex = /[{]{3}(. ?)[}]{3}/;

let netto = brutto.replace(regex, "{{1}}");
let paramArray = brutto.match(regex).map((e, i) => {return {i: e}});

let result = { value: netto, params: paramArray }
console.log(result);

I get

{
    "value": "hello {{1}}} world {{{'something else'}}} ... ",
    "params": [
        {
            "i": "{{{'something'}}}"
        },
        {
            "i": "'something'"
        }
    ]
}

that is not really close to the desired result...

CodePudding user response:

You can use a function as the replacement, and it can increment a counter.

You need to add the g modifier to the regexp to match repeatedly.

let brutto = "hello {{{'something'}}}} world {{{'something else'}}} ... ";
let regex = /[{]{3}(. ?)[}]{3}/g;

let counter = 0;
let paramArray = {};
let netto = brutto.replace(regex, (match, g1) => {
  counter  ;
  paramArray[counter] = g1;
  return `{{${counter}}}`;
});

result = {value: netto, params: paramArray};
console.log(result);

  • Related