0

I am using a piece of code to replace "Tags" by values in Strings My concern is that it only changes the first Tag encountered if it exists several times :(

const replaceTagsToValue = (obj, chaine) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), chaine)

const Tags = [
    { "{info_1}": "One" },
    { "{info_2}": "Two" },
    { "{info_3}": "Three" }
    // etc etc...
]

let input = "{info_1}-{info_2}-{info_3} | {info_3}-{info_2}-{info_1}";
let output = replaceTagsToValue(Tags, input);
console.log(output);

Result:

One-Two-Three | {info_3}-{info_2}-{info_1}

Want these result:

One-Two-Three | Three-Two-One

I tested with the addition of a global regex approach, without success of course:

.replace(/Object.keys(s)[0]/g, s[Object.keys(s)[0]])

Do you have a solution ? see a more suitable and more generic or best practice solution?

Thank's !

2
  • Based on your logic in replaceTagsToValue, shouldn't your expected output be One-Two-Three | Three-Two-One ? Commented Jul 29, 2020 at 14:26
  • yes it's right, it's a error of manual writing ;) i make the change... thank's Commented Jul 29, 2020 at 14:59

1 Answer 1

2

In this case you cannot use the literal notation (/Object.keys(s)[0]/g) to build a dynamic RegExp, you need to use the constructor (new RegExp(Object.keys(s)[0], 'g')) instead:

const replaceTagsToValue = (obj, inStr) => obj.reduce((f, s) => f.replace(new RegExp(Object.keys(s)[0], 'g'), s[Object.keys(s)[0]]), inStr)

const Tags = [
  { '{info_1}': 'One' },
  { '{info_2}': 'Two' },
  { '{info_3}': 'Three' }
  // etc etc...
]

const input = '{info_1}-{info_2}-{info_3} | {info_3}-{info_2}-{info_1}'
const output = replaceTagsToValue(Tags, input)
console.log(output)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes ! it work, u save my life ;) it's difficult to get all the great syntax when you begin in a new langage.. Thank's a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.