Home > front end >  Javascript dynamic string template to title
Javascript dynamic string template to title

Time:09-22

I have a string template that backend sends dynamically. Each table tab has a different label_pattern when user want to edit or delete a row we should build the title based on this pattern.. At the moment we use the hash id in the title (pop-up, when want to edit or delete a table row) but it is not descriptive..

The string template look like this:

label_pattern: "{{code}}, {{description}}, {{category}}"

We can also have access through props to the row we want to delete or edit and the object looks like this:

{
  category: "Fruit"
  code: "AP"
  description: "Green Apple"
  hash: "b45516ddda8566ee"
}

I used the split function to create an array from the label pattern:

 ['{{code}},', '{{description}},', '{{category}},']

The reason why it is important because the label_pattern on a different table tab maybe looks differently. So we always have to compare the active table pattern because they adjusted to the current tab's row object. I can access the active tab pattern and the row's data too. I just don't know how to iterate, map and replace through the pattern array in order to build the title text based on this..

CodePudding user response:

You can use a regex and a replacer function to replace the text with the objects properies:

const obj = 
{
  category: "Fruit",
  code: "AP",
  description: "Green Apple",
  hash: "b45516ddda8566ee",
};

const label_pattern = "{{code}}, {{description}}, {{category}}";

let label = label_pattern.replace(/{{(?<prop>\w )}}/g, function(match, p, offset, string, groups)
{
  return obj[groups.prop];
});

console.log(label);

CodePudding user response:

I think this should do the trick:

let label_pattern = "{{code}}, {{description}}, {{category}}".split(",");
let label_array = label_pattern.map((value) => { return value.trim().substring(2, value.trim().length-2) });

This considers your input string will always be in this format: "{{label1}}, {{label2}}, {{label3}} ..."

Explanation: I split the string with commas as you mentioned, then map each label we have and remove any trailing spaces. Then we find the substring in each string removing two characters from front and back.

Edit: Sorry for the bad indentation and formatting, I solved it in the console.

Edit 2: In order to extract the values from an object whose keys are as a string in the array (label_array in our case) the following code will work:

let obj = {
  "category": "Fruit",
  "code": "AP",
  "description": "Green Apple",
  "hash": "b45516ddda8566ee"
}

let values = label_array.map((key) => { return obj[key]});

In my execution the values was: ['AP', 'Green Apple', 'Fruit']

  • Related