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. }
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • blinkbits
  • BlinkList
  • blogmarks
  • BlogMemes
  • Blogosphere News
  • Blogsvine
  • blogtercimlap
  • Blue Dot
  • Bumpzee
  • co.mments
  • connotea
  • De.lirio.us
  • description
  • description
  • eKudos
  • Fark
  • feedmelinks
  • Fleck
  • Furl
  • Global Grind
  • Gwar
  • Haohao
  • HealthRanker
  • Hemidemi
  • Internetmedia
  • kick.ie
  • laaik.it
  • LinkaGoGo
  • LinkArena
  • Linkter
  • Live
  • Ma.gnolia
  • Meneame
  • MyShare
  • N4G
  • Netvouz
  • NewsVine
  • NuJIJ
  • PlugIM
  • description
  • Pownce
  • ppnow
  • Propeller
  • RawSugar
  • Rec6
  • Reddit
  • SalesMarks
  • Scoopeo
  • description
  • Segnalo
  • Shadows
  • Simpy
  • Sk-rt
  • Slashdot
  • Smarking
  • Socialogs
  • SphereIt
  • Spurl
  • StumbleUpon
  • Taggly
  • TailRank
  • Technorati
  • ThisNext
  • TwitThis
  • Webride
  • Wikio
  • Wists
  • Wykop
  • Xerpi
  • YahooMyWeb
  • Yigg
Leave a Reply

You must be logged in to post a comment. Login »