Last active
August 17, 2021 09:47
-
-
Save ioslh/00b3d736addcbfe994c86b5e9b73ceb8 to your computer and use it in GitHub Desktop.
tricky way to parse es6 template string
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
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
init