Skip to content

Instantly share code, notes, and snippets.

@me2resh
Last active May 30, 2022 13:39
Show Gist options
  • Save me2resh/2a0a38df5e5e1201d4fa4b08b0551522 to your computer and use it in GitHub Desktop.
Save me2resh/2a0a38df5e5e1201d4fa4b08b0551522 to your computer and use it in GitHub Desktop.
Replace multiple substrings in a string using reducer
const originalString = "I would love to eat apple and banana."
const wordsMap = {
'apple' : "mango",
'banana' : "grapes",
}
const replaceStrings = (value) => {
return Object.keys(wordsMap).reduce((result, oldString) => result.replace(new RegExp(oldString, 'g'), wordsMap[oldString]), value)
}
console.log(replaceStrings(originalString)) // Will output: "I would love to eat mango and grapes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment