简体   繁体   English

正则表达式以在URL中获取特定的查询字符串变量

[英]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. 我想使用正则表达式在上述URL中的“ action /”之后获取第一个字符,该字符为4。 Is it possible with regex in js, or is there any way? js中的正则表达式可能吗,还是有什么办法?

Use regex \\d+(?=\\/\\?) 使用正则表达式\\d+(?=\\/\\?)

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

Test code here . 在这里测试代码。

Using this regex in JavaScript: 在JavaScript中使用此正则表达式:

action/(.)

Allows you to access the first matching group, which will contain the first character after action/ -- see the examples at JSFiddle 允许您访问第一个匹配组,该组将包含action/后的第一个字符 action/ -请参见JSFiddle中的示例

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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