Skip to content

Instantly share code, notes, and snippets.

@ioslh
Last active August 17, 2021 09:47
Show Gist options
  • Save ioslh/00b3d736addcbfe994c86b5e9b73ceb8 to your computer and use it in GitHub Desktop.
Save ioslh/00b3d736addcbfe994c86b5e9b73ceb8 to your computer and use it in GitHub Desktop.
tricky way to parse es6 template string
const parseEs6String = (str: string, ctx: Record<string, string>) => {
return new Function(`
const proxy = new Proxy(${JSON.stringify(ctx)}, {
has() { return true },
get(obj, prop) {
if (prop === Symbol.unscopables) return false
if (prop in obj) return obj[prop]
if (prop in window) return window[prop]
return ''
}
})
with(proxy) {
return \`${str}\`
}
return ''
`)()
}
console.log(parseEs6String('hello ${name}', {name: 'world'})) // 'hello world'
@ioslh
Copy link
Author

ioslh commented Aug 17, 2021

init

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment