C
C
cester2020-05-15 15:44:31
JavaScript
cester, 2020-05-15 15:44:31

How to write a regular expression to replace by keys from an object?

How to write a regular expression so that it replaces strings with a value from an object?
Given a template: An object with the desired values:
const template = "{label} {text} {...}"

const obj = {
      label: 'some label',
      text: 'some text'
    }


The result should be like this: I understand that you need to use replace for this, the problem is in writing the regular expression itself.
const newStr = 'some label some text'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2020-05-15
@cester

newStr = template.replace(/{(.*?)}/g, (m,m1) => obj[m1])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question