Last active
May 30, 2022 13:39
-
-
Save me2resh/2a0a38df5e5e1201d4fa4b08b0551522 to your computer and use it in GitHub Desktop.
Replace multiple substrings in a string using reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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