Ad

Extract Numbers Between Two Patterns Javascript

- 1 answer

I am trying to extract a set of numbers from a url. The string is betwen the word "region" and word "all". The url is : http://my.site.com/theme/feature/region/227-84/all/country-south

The regular expression which I have built is :

var tmp = $(this).attr('link').match("(?=region/).*?(?=/all)");

The regex is extracting the correct portion of numbers but is always sticking the region to numbers so the extracted string become :

"region/227-84"

While I wannt to get only the numbers:

"227-84" 
Ad

Answer

It's including the substring "region/" because the positive lookahead (?=region\/) is matching the character before "region/". Since JavaScript doesn't have lookbehinds, the easiest option would be to remove the lookaheads and use a capturing group in order to extract the middle portion:

/region\/([^\/]*)\/all/

or if there are slashes between the patterns:

/region\/(.*?)\/all/

Usage:

var match = $(this).attr('link').match(/region\/([^\/]*)\/all/);
var result = match ? match[1] : null;

console.log(result); // "227-84"

If there is a match, the .match() method returns an array. In this case it would return:

["region/227-84/all", "227-84"] // match

The first capturing group has an index of one (i.e., match ? match[1] : null). In this case, the ternary operator is simply used to check if there was actually a match before accessing the array (otherwise an error would be thrown if there wasn't a match).

Ad
source: stackoverflow.com
Ad