code_junkie

Efficient Javascript String Replacement

Nov 13th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. <div id='sample'>
  2. <h4>%TITLE%</h4>
  3. <p>Text text %KEYWORD% text</p>
  4. <p>%CONTENT%</p>
  5. <img src="images/%ID%/1.jpg" />
  6. </div>
  7.  
  8. template = document.getElementById('sample');
  9. template = template.replace(/%TITLE%/, some_var_with_title);
  10. template = template.replace(/%KEYWORD%/, some_var_with_keyword);
  11. template = template.replace(/%CONTENT%/, some_var_with_content);
  12. template = template.replace(/%ID%/, some_var_with_id);
  13.  
  14. //Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output.
  15. function template(templateid,data){
  16. return document.getElementById(templateid).innerHTML.replace(/%(w*)%/g,function(m,key){return data.hasOwnProperty(key)?data[key]:"";});
  17. }
  18.  
  19. <div id="mytemplate">
  20. <p>%test%</p>
  21. <p>%word%</p>
  22. </div>
  23.  
  24. document.getElementById("my").innerHTML=template("mytemplate",{test:"MYTEST",word:"MYWORD"});
  25.  
  26. var user = {
  27. "firstName": "John",
  28. "login": "john_doe",
  29. "password": "test",
  30. };
  31.  
  32. var textbody = ""
  33. +"Hey {firstName},n"
  34. +"n"
  35. +"You recently requested your password.n"
  36. +"login: {login}n"
  37. +"password: {password}n"
  38. +"n"
  39. +"If you did not request your password, please disregard this message.n"
  40. +"";
  41.  
  42. textbody = textbody.replace(/{[^{}]+}/g, function(key){
  43. return user[key.replace(/[{}]+/g, "")] || "";
  44. });
  45.  
  46. element.innerHTML = (new Template(element.innerHTML)).evaluate({
  47. title: 'a title',
  48. keyword: 'some keyword',
  49. content: 'A bunch of content',
  50. id: 'id here'
  51. })
  52.  
  53. with(document.getElementById('sample'))
  54. {
  55. innerHTML = innerHTML.replace(a, A).replace(b, B).replace(c, C); //etc
  56. }
Add Comment
Please, Sign In to add comment