简体   繁体   中英

Regex to get a specific query string variable in a URL

I have a URL like

server/area/controller/action/4/?param=2"

in which the server can be

http://localhost/abc
https://test.abc.com
https://abc.om

I want to get the first character after "action/" which is 4 in the above URL, with a regex. Is it possible with regex in js, or is there any way?

Use regex \\d+(?=\\/\\?)

var url = "server/area/controller/action/4/?param=2"; 
var param = url.match(/\d+(?=\/\?)/);

Test code here .

Using this regex in JavaScript:

action/(.)

Allows you to access the first matching group, which will contain the first character after action/ -- see the examples at JSFiddle

这种方式将URL分割为/字符,并提取最后一个元素

var url = "server/area/controller/action/4/?param=2".split ('/').slice (-2,-1)[0]; 

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