-2

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...

serge
  • 13,940
  • 35
  • 121
  • 205
  • Why do you replace all ([if it would work](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#using_global_and_ignore_with_replace)) with `{{1}}` and not `1`, `2`, ...? – Andreas Mar 23 '22 at 19:02
  • `{i: e}` - Does not "magically" know that there's a `i` variable in the execution context and that it should replace the `i` in the object literal with its value and use that as the property -> [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) – Andreas Mar 23 '22 at 19:06
  • @Andreas, i is the index of the map function, please if you have an answer write your version – serge Mar 23 '22 at 19:33

1 Answers1

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    _"I need...a string containing two brackets and the values"_ - `value: "hello {{1}} world {{2}}...",` – Andreas Mar 23 '22 at 19:07