-1

Hello I would like to get the value of a one word query string and store that string into a variable.

For example if a user goes to:

www.mysite.com/example

I need some JS or jQuery to take the string example and store it into a variable for use in another function.

Ive done some research and found this question here, but these answers are more indepth, splitting the query string by &'s and stuff.

I just need to capture the value of one single word.

Thanks!

cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 2
    Please note in `www.mysite.com/example` there's no query string: `example` is the path. See https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax. So what do you really need? – Davide Cavestro Sep 18 '17 at 20:05

1 Answers1

2

You can accomplish this fairly quickly:

//var url = (document.URL);
var url = ('http://www.example.com/example');
var index = url.substr(url.lastIndexOf('/')+1);

Here is a jsFiddle to play with.

The code above uses document.URL to get the full URL of the current document.

Then substr starting at one more than the last index of /. This will leave you with everything after the last /.

However, if your URL looked like "http://www.example.com/example/" this would return nothing, an empty string. You'd have to do some additional work to account for that. This is why some examples would use .split() since you can then split the URL at every / and grab the item from an array.

In the spirit of providing not just an answer but the right one, I think a regular expression and .match() is the right way to go. This solution comes from a very similar question on StackOverflow.

var url = ('http://www.example.com/example/test/example2/');
var index = url.match(/\/([^\/]+)\/?$/)[1];

This will give you example2 regardless of a whether or not a trailing slash exists.

Here is a jsFiddle.

Jeramiah Harland
  • 854
  • 7
  • 15