Regular expression to find the word after the character and before the other, if included

I have a url:

image / media group / rugby league-program-covers-3436? Sort = Name

or

image / media group / rugby league-program-covers-3436

Do I need to get everything after the media group and not include it ? or something after.

So in both cases rugby-league-programme-covers-3436 is what I need to return

I used the regular expression /media-group/(.*)\? , which works for an instance where there is a query string, but not in an instance where there is no query string.

I am using the code below

 var patt=new RegExp('/media-group/(.*)\?'); return patt.exec(url)[1]; 

Your help in this will be rated most highly.

+4
source share
1 answer

I believe the best template would be:

 /^[^\#\?]+\/media-group\/([^\?]+).*$/ 

which breaks out like:

 ^ - start of string [^\#\?]+ - one or more non-hash, non-question-marks \/ - literal char media-group - literal chars \/ - literal char ( - start capture group [^\?]+ - one or more chars non-question-marks ) - end of capture group .* - zero or more chars $ - end of string 

The reason for this is that [^ \?] + Is greedy because it will try to match as long as possible, which covers either a question mark followed by arbitrary characters, or nothing, since all the characters to the end of the line are already written in the group capture without question marks.

So using

 var RE=new RegExp(/^[^\#\?]+\/media-group\/([^\?]+).*$/), url="image/media-group/rugby-league-programme-covers-3436?sort=title"; console.log(url.match(RE)[1]) 

prints: rugby-league-programme-covers-3436 and changing the url to image/media-group/rugby-league-programme-covers-3436 gives the same result.

Update

Changed the description of the David Furster template.

+5
source

Source: https://habr.com/ru/post/1491740/


All Articles