Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a value from an URL?

Asuming I have something like

var url = 'http://stackoverflow.com/questions/24a34b83c72/js-regex-get-values-between-two-characters'

How could I get the 24a34b83c72 ID using pure javascript? I know that it's always after the questions/ part and that regardless if it contains a number or symbol, it needs to end before the next /. I tried things like;

url.substring(url.lastIndexOf('questions/'))

But that resulted in the entire thread after it. I tried regular expresions but the closest I got to is:

var regex = /"details\/"[a-zA-Z0-9]+"\/"/

Can anyone help me?

like image 347
sgarcia.dev Avatar asked Apr 07 '16 23:04

sgarcia.dev


People also ask

How do you find the variable in a URL?

To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.

How do you give a URL a value?

To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.


1 Answers

You could group everything after questions/ and before the next /, like so:

url.match(/questions\/([^/]+)/)[1]

You can see the output of url.match(..) is this:

["questions/24a34b83c72", "24a34b83c72"]

The second item is there because of the parenthesis around [^/]+, so you access it with url.match(..)[1].

like image 61
Florrie Avatar answered Oct 25 '22 01:10

Florrie