A
A
Alex2014-05-24 08:25:35
JavaScript
Alex, 2014-05-24 08:25:35

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://"}
  ]}

What is the fastest way to get the following html code:
<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

3 answer(s)
D
Damir Makhmutov, 2014-05-24
@doodoo

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)

You can write a simple function:
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);
    };
})();

And use 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 += simpleTemplate(jsonData.html, item);
});

console.log(result)

E
Eugene Obrezkov, 2014-05-24
@ghaiklor

Use replace to render html.

M
mrDinckleman, 2014-05-24
@mrDinckleman

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 question

Ask a Question

731 491 924 answers to any question