Skip to content

Instantly share code, notes, and snippets.

@catpea
Forked from smeijer/parse-es6-template.js
Created October 26, 2024 03:15
Show Gist options
  • Save catpea/c52aa4492664feba176fe7ce117e4159 to your computer and use it in GitHub Desktop.
Save catpea/c52aa4492664feba176fe7ce117e4159 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 parseTpl(template, map, fallback) {
return template.replace(/\$\{.+?}/g, (match) => {
const path = match.substr(2, match.length - 3).trim();
return get(path, map, fallback);
});
}
export default parseTpl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment