Last active
June 1, 2019 17:26
-
-
Save mmis1000/f1a3b6256b1eb6b58983e5bb81f83ed2 to your computer and use it in GitHub Desktop.
Regex is fun (
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
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