JSFiddle - React, Tailwind, and code Playground
JavaScript
/*
the sample are in line 42
open the console to see the result
*/
/* definition */
function replaceVars(objSource, objReplacer){
var pattern = replaceVars.pattern;
if(typeof objSource === "object" ){
if(objSource === null) return null;
if(objSource instanceof Array){
for(var i = 0; i < objSource.length; i++){
objSource[i] = replaceVars(objSource[i], objReplacer);
}
}else{
for(var property in objSource){
objSource[property] = replaceVars(objSource[property], objReplacer);
}
}
return objSource;
}
if(typeof objSource === "string"){
return objSource.replace(pattern, function(finded, varName){
return varName in objReplacer ? objReplacer[varName] : finded;
});
}
return objSource;
}
replaceVars.pattern = /\*\*([0-9a-z_$]{1,})\*\*/gi;
/* sample */
var objValues = {
name: "Foo Bar Baz",
value: 15,
url: "http://stackoverflow.com/users/1704264/luan-castro"
};
var obj = {
children: ["hello **name**"],
foo: {
internal: {
inner: "**url**"
},
age: "**value** years"
}
}
docment.write(replaceVars(obj, objValues));