Amanda
Amanda

Reputation: 2163

Substituting matched characters with a value from object

I have a string as follows:

{hours}/DP1/{facilityId}/CP23/{minutes}

and have an object which is:

{
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
}

I want to get the output string as :

4/DP1/abd-rtyo-99e/CP23/43

thus replacing any token inside {} with a value from object. So hours inside {} gets replaced with 4 from the object, minutes by 43 and so on. How could I do this?

I could detect characters inside {} using a regular expression like {\w+} but don't know how to proceed with it.

Upvotes: 2

Views: 37

Answers (3)

The fourth bird
The fourth bird

Reputation: 163477

Another option could be to use Object.entries and use the key and value in the replacement:

let obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
};
let str = '{hours}/DP1/{facilityId}/CP23/{minutes}';
Object.entries(obj).forEach(([key, value]) => {
  str = str.replace(`{${key}}`, value);
});

console.log(str);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371029

One option is to match word characters, and use a replacer function which checks to see if the key exists on the object - if so, return the associated value:

const input = '{hours}/DP1/{facilityId}/CP23/{minutes}';
const obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
};
const output = input.replace(
  /{(\w+)}/g,
  (match, possibleKey) => obj[possibleKey] ? obj[possibleKey] : match
);
console.log(output);
// 4/DP1/abd-rtyo-99e/CP23/43

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36594

You can loop through all the keys of object using for..in and then replace() the key in original string with the value of key

let str = '{hours}/DP1/{facilityId}/CP23/{minutes}'

const obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
}
let result = str;
for(let k in obj){
  result = result.replace(`{${k}}`,obj[k]);
}
console.log(result)

Upvotes: 1

Related Questions