Ifedi Okonkwo
Ifedi Okonkwo

Reputation: 3656

Javascript Regexp replace multiple strings matching property names of another object literal

I have these declared:

var obj = {aaa: "came", bbb: "saw", ccc: "conquered", zzz: "discarded" };

var str = "I {aaa}, I {bbb}, I {ccc}. Then I {aaa} again."

What I want to do is str.replace() each curly braced string with the appropriately named property from obj. So in the end, I should have:

I came, I saw, I conquered. Then I came again.

Thank you.

EDIT: The linked duplicate indeed proved very appropriate for my case. In addition, answers on that question actually provide dynamic solutions for the case where I did not know the properties of obj ahead of time.

Upvotes: 1

Views: 53

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can use callback function of replace method

var obj = {aaa: "came", bbb: "saw", ccc: "conquered", zzz: "discarded" };
var str = "I {aaa}, I {bbb}, I {ccc}. Then I {aaa} again."

let op = str.replace(/\{([^}]+)\}/g, (_,g1)=> obj[g1] || _)

console.log(op)

Upvotes: 3

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

Easiest and elegant approach is to use string interpolation

var obj = {aaa: "came", bbb: "saw", ccc: "conquered", zzz: "discarded" };

var str = `I ${obj.aaa}, I ${obj.bbb}, I ${obj.ccc}. Then I ${obj.aaa} again.`

console.log(str);

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371039

Capture what comes between {}s, and use a callback for the replacer to look up that captured property on the object:

var obj = {aaa: "came", bbb: "saw", ccc: "conquered", zzz: "discarded" };
var str = "I {aaa}, I {bbb}, I {ccc}. Then I {aaa} again.";

const output = str.replace(/{([^}]+)}/g, (_, prop) => obj[prop]);
console.log(output);

Upvotes: 4

Related Questions