6

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!

1
  • Is this MVC? Normally a parameter in a URL would have the form ?parm=xxx&parm2=yyy. Commented Mar 15, 2013 at 15:10

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

10 Comments

that doesn't work. That gets "/"
and if the url is a string, like the OP has used for an example?
the empty string at path[0] is not because it is a zero-based array. It's because the value at path[0] is empty. likely because the string being split is "/example/test/search"
@musefan He said: How do I get the "test" from the url using the javascript. Never mentioned the URL being a string, therefore I assumed going for window.location.pathname would be a good call.
yeah, get "test" from the url he provided, he didn't say he was running the script on that exact page. Though it may turn out it is the case. You should expand your answer to show both methods
|
0

Try URI.js. In particular, the segment() method should give you what you need.

1 Comment

Voting down because a library suggestion should just be a comment. The question implied a vanilla javascript solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.