Created
May 27, 2020 22:06
-
-
Save chrisgfortes/882dda06403201eb3e194f812ba04b39 to your computer and use it in GitHub Desktop.
Replace text with an identifier #{key}
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
/** | |
* @param {string} text - Text with replacement keys identified by #{key} | |
* @param {object} replacements - An object used to replace keys from text | |
* @return {string} string replaced | |
*/ | |
const replace = (text = "", replacements = {}) => { | |
const pattern = /#\{(.*?)\}/g; | |
const keys = text.match(pattern) || []; | |
return keys.reduce((acc, key) => { | |
const pureKey = key.replace(pattern, '$1'); | |
const replacement = replacements[pureKey] || key; | |
return acc.replace(key, replacement); | |
}, text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment