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.
-
function get_substring (s,pattern_obj)
-
{
-
// Note: S = string, pattern is an optional object of start and end pair values
-
-
// see if pattern has been set - if not, use the default being and end
-
if (!pattern_obj.begin || !pattern_obj.end)
-
{
-
pattern_obj.begin = "<!– begin –>";
-
pattern_obj.end = "<!– end –>";
-
-
}
-
var pattern=pattern_obj.begin;
-
var re = new RegExp(pattern,"m");
-
var m;
-
re.multiline= true;
-
-
if (m = re.exec(s))
-
{
-
-
} else {
-
return false;
-
-
}
-
var start = m.index+pattern.length;
-
-
var pattern=pattern_obj.end;
-
var re = new RegExp(pattern,"m");
-
re.multiline= true;
-
-
m = re.exec(s);
-
if (!m) return false;
-
-
var end =m.index;
-
var result= s.substr(start,end-start);
-
-
return result;
-
}













































































Entries (RSS)