Peter
Peter

Reputation: 685

Get the end of string with Javascript

I am storing a string (url) in a variable it can look like one/two/three/test.aspx?ID=12312 I want to extract the querystring value, not from window.location but from the html

I thought I could use substring and write

var link = ($(this).find('a').attr('href')); 
var qs = link.substring( link.indexOf("="),  text.indexOf(" ") )

but it returns the string before the = and not after.

What am I doing wrong? Thanks in advance.

Upvotes: 0

Views: 2986

Answers (4)

Damien Goor
Damien Goor

Reputation: 91

Another way could be:

var qs = link.split("=").pop();

Upvotes: 0

naikus
naikus

Reputation: 24472

A while ago, I'd written a short function for this:

  /**
   * Gets the query parameters of the given URI as a associative array or map
   * e.g. Given a URI http://www.level3labs.com/jaf?foo=bar&baz=bazzm, will
   * give {"foo":"bar", "baz":"bazzm"}
   * @param {URI} strUri The uri with a query
   * @return Object containing query params or and empty object 
   */
  function getQueryParams(strUri)   {
     var paramMap = {};
     if(!!strUri)   {
        return paramMap;
     }

     var strQuery = strUri.substring(strUri.indexOf("?"));
     if(strQuery && strQuery.indexOf("?") === 0 && strQuery.length > 1) {
        strQuery = strQuery.substring(1);
        var paramValArr = strQuery.split("&");
        for(var i = 0, len = paramValArr.length; i < len; i++)   {
           var paramVal = paramValArr[i];
           var delimIdx = paramVal.indexOf("=");

           var param = null;
           var val = null;
           if(delimIdx >= 0) {
              param = unescape(paramVal.substring(0, delimIdx));
              val = unescape(paramVal.substring(delimIdx + 1));
           }else {
              param = unescape(paramVal);
           }
           paramMap[param] = val;
        }
     }
     return paramMap;
  }

Upvotes: 3

Falle1234
Falle1234

Reputation: 5063

Try this instead

var link = ($(this).find('a').attr('href')); 
var qs = link.substring( link.indexOf("="));

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80880

Just omit the second parameter. In this case, should return the end of the string starting at the provided index.

Upvotes: 0

Related Questions