Ad

Regex Expression To Remove Whitespaces Between {{ }}

- 1 answer

I am having issue building up the regex expression for the following problem :-

Here is my following code :-

let modifiedData = ecData.info.slice(0, 1);
      let keys = Object.keys(modifiedData[0])
      this.previewData = this.htmlBody
      keys.forEach((key) => {
        this.previewData = this.previewData.replace(`{{${key}}}`, modifiedData[0][key]);
    });

Here what I am doing is rendering the html output in the modal.

Now say i have a object for example :-

let abc = { city: "mumbai", name: "ronak"};

Now my output is right when i am sending data like <p>{{city}}</p> so the rendered html is mumbai but when I am writing code like this <p>{{ city }}</p> so it is rendering the same output <p>{{ city }}</p> so I want a regex so that it can remove the start and end whitespaces including {{ }}, So how should I do it ?

Any help would be appreciated..

Ad

Answer

Maybe this snippet can help?

const data = {
  name: 'Ari',
  age: 26,
  city: 'Tokyo'
};

const template = "Hello, my name is {{name}} and I'm {{ age}} years old and currently I'm living in {{ city }}.";

const replaced = template.replace(/{{\s*(\w+)\s*}}/g, (_, key) => data[key]);

console.log(replaced);

You can also check here to see how replacer function works in String.prototype.replace

Ad
source: stackoverflow.com
Ad