Skip to content

Instantly share code, notes, and snippets.

@joeldbirch
Last active June 30, 2021 07:36
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 joeldbirch/c6b05cab0fb813169a153d8a79fefa3c to your computer and use it in GitHub Desktop.
Save joeldbirch/c6b05cab0fb813169a153d8a79fefa3c to your computer and use it in GitHub Desktop.
// moustache replacement
const soupStrainer = (template, values) =>
[...template.matchAll(/\{\{([^}]*)\}\}/gi)].reduce(
(acc, [full, path]) =>
acc.replace(
full,
path.split(`.`).reduce((acc, curr) => acc[curr], values)
),
template
)
// your values to swap in
const values = {
dealership: {
name: `Joel's Shonky Dealership`,
street: `Shonk Avenue`,
},
}
// your template string
const template = `At {{dealership.name}} located on {{dealership.street}}`
// how to use soupStrainer
const result = soupStrainer(template, values)
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment