Skip to content

Instantly share code, notes, and snippets.

@dz-s
Forked from smeijer/parse-es6-template.js
Last active May 23, 2018 11:52
Show Gist options
  • Save dz-s/80afaf333996b3193d993b33a7541234 to your computer and use it in GitHub Desktop.
Save dz-s/80afaf333996b3193d993b33a7541234 to your computer and use it in GitHub Desktop.
ES6 template string parser
import parseTpl from './parse-es6-template';

parseTpl('${name} is now master of the ${galaxy}', { 
  name: 'John',
  galaxy: 'Milky Way',
});
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