Skip to content

Instantly share code, notes, and snippets.

@mmis1000
Last active June 1, 2019 17:26
Show Gist options
  • Save mmis1000/f1a3b6256b1eb6b58983e5bb81f83ed2 to your computer and use it in GitHub Desktop.
Save mmis1000/f1a3b6256b1eb6b58983e5bb81f83ed2 to your computer and use it in GitHub Desktop.
Regex is fun (
function unescape(str) {
return str.replace(/\\.|./g, (str)=>str.slice(str.length - 1))
}
function format(template: string, obj: {[key: string]: string}) {
return template.replace(/\\.|\{(?:\\.|[^\}])+\}|./g, function (str) {
if (/^\{.+\}$/.test(str)) {
return obj[
unescape(str.slice(1, str.length - 1))
]
}
if (str.length === 2) {
return str.slice(1)
}
return str
})
}
console.log(format('{\\{}1\\, 2{\\}}', { '{': '(', '}': ')'}))
console.log(format('\\{{\\\\\\{}1\\, 2{\\}}\\} {\\{1, 2\\}}', { '\\{': '(', '}': ')', '{1, 2}': 'zzz'}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment