Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting second path element from url using javascript [duplicate]

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!

like image 885
jewelwast Avatar asked Mar 15 '13 15:03

jewelwast


1 Answers

No need for regex's here. This should do the trick:

When working with current url

var path = window.location.pathname.split("/");
// Use path[2] to get 'test'

When working with any url as a string:

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.

like image 112
Robin van Baalen Avatar answered Oct 20 '22 08:10

Robin van Baalen