import parseTpl from './parse-es6-template';
parseTpl('${name} is now master of the ${galaxy}', {
name: 'John',
galaxy: 'Milky Way',
});
-
-
Save dz-s/80afaf333996b3193d993b33a7541234 to your computer and use it in GitHub Desktop.
ES6 template string parser
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 get(path, obj, fb = `$\{${path}}`) { | |
return path.split('.').reduce((res, key) => res[key] || fb, obj); | |
} | |
function parse(template, map, fallback) { | |
return template.replace(/\$\{.+?}/g, (match) => { | |
console.log('match', match); | |
const path = match.substr(2, match.length - 3).trim(); const replBy = get(path, map, fallback); | |
return isFinite(replBy) ? replBy : '\"'+replBy+'\"'; | |
}); | |
} | |
export default parseTpl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment