Archive for the “Javascript” Category


I am so tired of looking at many regex (regular expression) examples for Javascript that look good, and are very verbose, but ultimately do not provide any code that can help you solve a real world problem!

Here’s a function that I use in conjunction with Ext-JS on some legacy templates. I take the search results from an Ajax call, feed the response string and do a search and replace on the HTML returned, to grab certain portions of the page I made the Ajax call to. I’ll have more examples about this type of usage in a future post, but hopefully many of you will find this get substring function using regex, simple and useful.

  1. function get_substring (s,pattern_obj)
  2. {
  3. // Note:  S = string, pattern is an optional object of start and end pair values
  4.  
  5. // see if pattern has been set - if not, use the default being and end
  6. if (!pattern_obj.begin || !pattern_obj.end)
  7. {
  8. pattern_obj.begin = "<!– begin –>";
  9. pattern_obj.end = "<!– end –>";
  10.  
  11. }
  12. var pattern=pattern_obj.begin;
  13. var re = new RegExp(pattern,"m");
  14. var m;
  15. re.multiline= true;
  16.  
  17. if (m = re.exec(s))
  18. {
  19.  
  20. } else {
  21. return false;
  22.  
  23. }
  24. var start = m.index+pattern.length;
  25.  
  26. var pattern=pattern_obj.end;
  27. var re = new RegExp(pattern,"m");
  28. re.multiline= true;
  29.  
  30. m = re.exec(s);
  31. if (!m) return false;
  32.  
  33. var end =m.index;
  34. var result= s.substr(start,end-start);
  35.  
  36. return result;
  37. }

Comments No Comments »