Search code examples
javascriptvariablesmethodsreplacereplaceall

How can I use variables as the pattern and the replacement of replaceAll() method?


I have a form, and once the submit button is clicked, an object is generated. Each key-value pair is built following this pattern: inputId: inputValue, so the object looks like this:

let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

I then need to replace all instances of the inputIds inside a string. So the string looks like this:

let template = "My name is agentsName and this is my phone number: agentsPhone"

and I need to make it look like this:

"My name is John and this is my phone number: 000-000-0000"

The number of input fields is unknown (since it depends on other things) and they won't always be the same. So I'm trying to create a function to replace these placeholders dynamically. I'm trying to loop through the inputsObj and then replace each key with its value:

let finalTemplate

const getReplacements = () => {
   for (let replacement in inputsObj) {
       finalTemplate = template.replaceAll(replacement, inputsObj[replacement])
            return finalTemplate
   }
   return finalTemplate
}

For example, replacement would be agentsName and inputsObj[replacement] should be John (and it would loop through the entire object in order to get all of the key-value pairs).

But this doesn't work. I'm guessing it's because I'm trying to use variables as the pattern and the replacement (it did work when I tried using regular strings instead, so I know everything else is working fine). But I don't know how to solve this. Any ideas?

EDIT: I tried using template literals and it didn't work


Solution

    1. You can't return in first iteration of the loop
    2. You have to use replaceAll on finalTemplate

    let inputsObj = {
      templateList: 'blank',
      agentsName: 'John',
      agentsPhone: '000-000-0000'
    }
    
    let template = "My name is agentsName and this is my phone number: agentsPhone"
    
    const getReplacements = () => {
      let finalTemplate = template
    
      for (let replacement in inputsObj) {
        finalTemplate = finalTemplate.replaceAll(replacement, inputsObj[replacement])
      }
      return finalTemplate
    }
    
    console.log(getReplacements())