Skip to content

Instantly share code, notes, and snippets.

@bhanuwealthy
Created December 9, 2022 08:48
Show Gist options
  • Save bhanuwealthy/cfe0c730c52dc5167676f93a8ebc806c to your computer and use it in GitHub Desktop.
Save bhanuwealthy/cfe0c730c52dc5167676f93a8ebc806c to your computer and use it in GitHub Desktop.
How to render a string from a json context?
// Either extend the String prototype or use it as independent func
String.prototype.interpolate = function(props) {
    return this.replace(/\{(\w+)\}/g, function(match, expr) {
        return (props || window)[expr];
    });
};


var obj1 = {"template": "Hi, {var1} is {var2}",
            "context": "{\"var1\": null, \"var2\": null}"};

// raw template value 
obj1.template
>> 'Hi, {var1} is {var2}'


// find the context 
var context = JSON.parse(obj1.context)
context
>> {var1: null, var2: null}

context.var1 = "bhanu"
>> 'bhanu'
context.var2 = "a developer"
>> 'abc123ABC'

>>obj1.template.interpolate(context)
'Hi, bhanu is a developer'

DISCLAIMER: This code snippet doesn't belong to any Individual/Organisation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment