How do I do the following?
I have the following url
http://www.example.com/example/test/search
How do I get the "test" from the url using the javascript?
I would like to have a function that I call q = getUrlVars() and when I do q[1] it should give me the "test" (or parameter after second slash) from the url.
I am new to javascript. I know regex expressions is the way to get started, but I am not sure how to use that to get what I need. Thanks!
No need for regex's here. This should do the trick:
var path = window.location.pathname.split("/");
// Use path[2] to get 'test'
var strUrl = "http://www.example.com/example/test/search";
var path = strUrl.replace(/^https?:\/\//, '').split('/');
// Use path[2] to get 'test'
Note that path
will be a zero-based Array
, therefore you would assume going for path[1]
would do the trick. In this case however, path[0]
will return the first result of .split()
, an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With