Javascript ES5 method for interpolating string

139 Views Asked by At

I do not have access to string interpolation in our javascript engine and I need to create a solution for replacing all items in a string with previously defined variables. This needs to also work with nested variables.

I am trying something like:

var vars = {
    obj: [
        { "id": "test" }
    ],
    step1: "obj",
    step2: "0",
    step3: "id"
};
var interp = function(str) {
    var matched = false;
    str = str.replace(/{([^{}]*)}/g, function(match, p1) {
        matched = true;
        return p1.split(/(?=\[)/).reduce((o, p) => o[p[0] == '[' ? p.slice(1, -1) : p], vars) || p1;
    });
    if (matched) interp(str);
    return str;
}
var testStr = 'The string is currently: {{step1}[{step2}][{step3}]}';
console.log( interp(testStr) );
// Output:
// The string is currently: {obj[0][id]}

However if I change testStr to:

var testStr = 'The string is currently: {obj[0][id]}';
// Output:
// The string is currently: test

Why does it seem to skip past the outer-most capture and never return to it?

0

There are 0 best solutions below