简体   繁体   中英

Regex to Match URL with a Specific Query Param (Javascript)

I need to match a set of URLs and they all must contain a specific query param

(type=VCL)

So far I have /http:\\/\\/myhost:8080\\/organization\\/(\\d*)\\/mediaResource?.*$/

Which matches urls formed like http://myhost:8080/organizaton/5/mediaResource?anyParam(s) but I need to only get matches if the the URL contains the query param type=VCL

like: http://myhost:8080/organization/5/mediaResource?someParam=foo&type=VCL

Can someone help with the last part of the regex to get only URLs that contain the query param I care about?

You can use the following regex:

http:\/\/myhost:8080\/organization\/(\d*)\/mediaResource\?\S*\btype=VCL\b\S*

See demo

I only added a slash before the ? so that it was matched literally, added \\S* matching 0 or more non-whitespace symbols, and \\btype=VCL\\b so that only those URLs that have this param are matched.

I'd strongly recommend using a URI parser for this - it's easier to read and more maintainable and someone has done the work of testing the constituent regexes.

I've had good success with this lightweight one:

http://blog.stevenlevithan.com/archives/parseuri

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM