Hey there, I’ve got a block of HTML that I’m going to be using repeatedly (at various times during a users visit, not at once). I think that the best way to accomplish this is to create an HTML div, hide it, and when needed take its innerHTML and do a replace() on several keywords. As an example HTML block…
<div id='sample'> <h4>%TITLE%</h4> <p>Text text %KEYWORD% text</p> <p>%CONTENT%</p> <img src='images/%ID%/1.jpg' /> </div>
Would the best way to replace those keywords with dynamic data be to go…
template = document.getElementById('sample'); template = template.replace(/%TITLE%/, some_var_with_title); template = template.replace(/%KEYWORD%/, some_var_with_keyword); template = template.replace(/%CONTENT%/, some_var_with_content); template = template.replace(/%ID%/, some_var_with_id);
It just feels like I’ve chosen a stupid way to do this. Does anyone have any suggestions on how to do this faster, smarter, or better in any way? This code will be executed fairly often during a users visit, sometimes as often as once every 3-4 seconds.
Thanks in advance.
I doubt there will be anything more efficient. The alternative would be splitting it into parts and then concatenating, but I don’t think that would be much efficient. Perhaps even less, considering that every concatenation results in a new string which has the same size as its operands.
Added: This is probably the most elegant way to write this. Besides – what are you worried about? Memory usage? It’s abundant and Javascript has a decent memory manager. Execution speed? Then you must have some gigantic string. IMHO this is good.