Javascript – Efficient Javascript String Replacement

javascriptperformancereplacestring

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.

Best Answer

It looks like you want to use a template.

//Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output. 
function template( templateid, data ){
    return document.getElementById( templateid ).innerHTML
      .replace(
        /%(\w*)%/g, // or /{(\w*)}/g for "{this} instead of %this%"
        function( m, key ){
          return data.hasOwnProperty( key ) ? data[ key ] : "";
        }
      );
}

Explanation of the code:

  • Expects templateid to be the id of an existing element.
  • Expects data to be an object with the data.
  • Uses two parameters to replace to do the substitution:
  • The first is a regexp that searches for all %keys% (or {keys} if you use the alternate version). The key can be a combination of A-Z, a-z, 0-9 and underscore _.
  • The second is a anonymous function that gets called for every match.
  • The anonymous function searches the data object for the key that the regexp found. If the key is found in the data, then the value of the key is returned and that value will be replacing the key in the final output. If the key isn't found, an empty string is returned.

Example of template:

<div id="mytemplate">
  <p>%test%</p>
  <p>%word%</p>
</div>

Example of call:

document.getElementById("my").innerHTML=template("mytemplate",{test:"MYTEST",word:"MYWORD"});