Reputation: 2163
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
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
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
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