code_junkie

Regex match question

Nov 12th, 2011
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. <h2>{title}</h2>
  2. <p><a href="{url}">{content}</a></p>
  3.  
  4. ['title', 'url', 'content']
  5.  
  6. var pattern = new RegExp("{[a-zA-Z]+}+");
  7. var match = pattern.exec("{Sample} bob {text}");
  8.  
  9. var pattern = new RegExp("{[a-zA-Z]+}", "g");
  10.  
  11. var pattern = /{[a-zA-Z]+}/g;
  12.  
  13. var matches = "{Sample} bob {text}".match(pattern);
  14.  
  15. var pattern = new RegExp("{[a-zA-Z]+}+", "g");
  16.  
  17. <script>
  18. var text = '<h2>{title}</h2>n<p><a href="{url}">{content}</a></p>';
  19. var regex = /{[a-z]+}/ig;
  20. var result = text.match(regex);
  21. for (var i = 0; i < result.length; i++) {
  22. console.debug(i + ". " + result[i]);
  23. }
  24. /*
  25. gives:
  26. 0. {title}
  27. 1. {test}
  28. 2. {url}
  29. 3. {content}
  30. */
  31. </script>
  32.  
  33. String.prototype.template = function (obj) {
  34. return this.replace(/{([^{}]+)}/g,
  35. function (full, word) {
  36. return((typeof obj[word]==='string'||typeof obj[word]==='number')?obj[word]:full);
  37. }
  38. );
  39. };
  40.  
  41. "The {adj1} {adj2} {noun}.".template({adj1: 'lazy',adj2: 'brown', noun: 'dog'})
  42. ==> "The lazy brown dog."
Add Comment
Please, Sign In to add comment