3

url: testPage?id=67346756384/indexList

how to get the location of the id from the above url? I tried this:

getIdLocation = $(location).attr("href");
id = getIdLocation.substring(getIdLocation.lastIndexOf("/") + 1);

but that gets me "indexList". I need the id.Any ideas?? Thanks!

user1234
  • 3,000
  • 4
  • 50
  • 102
  • 2
    possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Shelvacu Sep 02 '15 at 22:09
  • possible duplicate of [How to get the value from the URL parameter?](http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter) – falinsky Sep 02 '15 at 22:10

2 Answers2

2

I have used this function, it works great.

It will be something like this for your case, pretty simple:

var id = GetURLParameter('id');

Full code from the link:

function GetURLParameter(sParam){
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

Although, I prefer to pass the url as a parameter. It will be easier to write unit tests for that.

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
0

Use the first and second parameters of substr to designate the start and length of the string to be extracted:

var id = str.substring(str.lastIndexOf("=")+1,str.lastIndexOf("/"));
GluePear
  • 7,244
  • 20
  • 67
  • 120