aboutsummaryrefslogtreecommitdiffhomepage
path: root/interpolate.js
blob: 36cf2f81f63e6fa16888e3af6e5bf731d2664f3a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
const regex = /\${[^{]+}/g;

export default function interpolate(template, variables, fallback) {
    return template.replace(regex, (match) => {
        const path = match.slice(2, -1).trim();
        return getObjPath(path, variables, fallback);
    });
}

//get the specified property or nested property of an object
function getObjPath(path, obj, fallback = '') {
    return path.split('.').reduce((res, key) => res[key] || fallback, obj);
}