0

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!

2
  • 1
    Are keys always a single character or also substrings? Commented Oct 13, 2019 at 18:23
  • For now, they will always be single characters, though that may change in the future. It is preferable that the solution works with any substrings, but it isn't necessary. Commented Oct 13, 2019 at 18:29

2 Answers 2

1

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"));

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

Comments

1

You can join keys to build a regex and then replace accordingly

function findreplace(inputStr) {
  let values = { "a": "A", "B": "x", "c": "C" };
  let regex = new RegExp("\\b" + Object.keys(values).join('|') + "\\b", 'g')
  return inputStr.replace(regex, (m) => values[m] )
}

console.log(findreplace('aBc'))
console.log(findreplace('AbC'))
console.log(findreplace('ABC'))

Comments

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.