Skip to content

Instantly share code, notes, and snippets.

@chrisgfortes
Created May 27, 2020 22:06
Show Gist options
  • Save chrisgfortes/882dda06403201eb3e194f812ba04b39 to your computer and use it in GitHub Desktop.
Save chrisgfortes/882dda06403201eb3e194f812ba04b39 to your computer and use it in GitHub Desktop.
Replace text with an identifier #{key}
/**
* @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