Answer the question
In order to leave comments, you need to log in
What is the fastest way to replace text in javascript?
i get json
{"html":"<div id="user%%userid%%"><span>You're ID: %%userid%%</span><img src="%%userimg%%"></div>",
"data": [{"userid":"11", "userimg":"http://"},
{"userid":"22", "userimg":"http://"}
]}
<div id="user11"><span>You're ID: 11</span><img src="http://"></div>
<div id="user22><span>You're ID: 22</span><img src="http://"></div>
Answer the question
In order to leave comments, you need to log in
Yes, something like this:
var jsonData = {
"html": "<div id=\"user%%userid%%\"><span>You're ID: %%userid%%</span><img src=\"%%userimg%%\"></div>",
"data": [{"userid":"11", "userimg":"http://"},
{"userid":"22", "userimg":"http://"}
]};
var result = "";
jsonData.data.forEach(function(item) {
result += jsonData.html
.replace(/%%userid%%/g, item.userid)
.replace(/%%userimg%%/g, item.userimg)
});
console.log(result)
var simpleTemplate = (function() {
var replaceByObject = function(template, values) {
for (var key in values) {
if (values.hasOwnProperty(key)) {
var pattern = ['%%', key, '%%'].join(''),
keyRegexp = new RegExp(pattern, 'g');
template = template.replace(keyRegexp, values[key]);
}
}
return template;
};
return function(template, values) {
return replaceByObject(template, values);
};
})();
var jsonData = {
"html": "<div id=\"user%%userid%%\"><span>You're ID: %%userid%%</span><img src=\"%%userimg%%\"></div>",
"data": [{"userid":"11", "userimg":"http://"},
{"userid":"22", "userimg":"http://"}
]};
var result = "";
jsonData.data.forEach(function(item) {
result += simpleTemplate(jsonData.html, item);
});
console.log(result)
jsfiddle.net/6PaaV
jQuery is only used to display the content, it is optional to include it
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question