javascriptfind-replace

How to use str.replace with many find/replace pairs in JavaScript


I need a function in JavaScript that takes one string as input, replaces many substrings with their corresponding values, then returns the result. For example:

function findreplace(inputStr) {
    const values = {"a": "A",
              "B": "x",
              "c": "C"};

    // In this example, if inputStr is "abc", then outputStr should be "AbC".

    return outputStr
}

I know how to individually find and replace, but I was wondering if there was an easy way to do this with many pairs of (case-sensitive) values at once.

Thank you!


Solution

  • Just iterate over values with the help of Object.entries(values):

    function findreplace(inputStr) {
      const values = {
        "a": "A",
        "B": "x",
        "c": "C"
      };
      for (const [search, replace] of Object.entries(values)) {
        inputStr = inputStr.replace(search, replace);    
      }
      return inputStr;
    }
    
    console.log(findreplace("abc"));