gandil
gandil

Reputation: 5418

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?

Upvotes: 0

Views: 506

Answers (3)

HBP
HBP

Reputation: 16033

This way splits the URL on the / characters and extracts the last but one element

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

Upvotes: 1

Code Jockey
Code Jockey

Reputation: 6721

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

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

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

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

Test code here.

Upvotes: 3

Related Questions