Skip to content

Instantly share code, notes, and snippets.

@BicanMarianValeriu
Last active April 17, 2020 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BicanMarianValeriu/af0aeac7624dcd56d929724ef35b97ea to your computer and use it in GitHub Desktop.
Save BicanMarianValeriu/af0aeac7624dcd56d929724ef35b97ea to your computer and use it in GitHub Desktop.
Fanciest Variable Mapping over a string
const variables = {
name: 'Bican Marian Valeriu',
job: 'WordPress Developer',
};
const destruct = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {});
const mapVariables = (variables, string) => {
let rxp = /{{([^}]+)}}/g, curMatch;
while (curMatch = rxp.exec(string)) {
const trimd = curMatch[1].trim();
const found = destruct(variables, trimd);
if (found[trimd] === undefined) continue;
string = string.replace(new RegExp(`{{${curMatch[1]}}}`, 'g'), found[trimd]);
}
return string;
};
const output = mapVariables(variables, '{{ name }} is a {{job}} at MyZone Media.' );
console.log( output );
// Output if all vars are found
// Bican Marian Valeriu is a WordPress Developer at MyZone Media.
// Output if just some of the vars are found
// Bican Marian Valeriu is a {{job}} at MyZone Media.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment