2

How do I extract "test" from the following URL?

http://www.example.com/index.php?q=test&=Go

I've found the a script to extract the path (window.location.pathname), but I can't find or figure out how to extract or split the URL.

-ben

ben
  • 21
  • 2
  • I believe that this question [Parse query string in JavaScript](http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript) has the solution. – Justin Mar 03 '11 at 02:53

3 Answers3

5
var m = window.location.search.match(/q=([^&]*)/);

if (m) { 
    alert(m[1]); // => alerts "test"
} 
James
  • 109,676
  • 31
  • 162
  • 175
  • This doesn't work if there are parameters that end in q, example `?iq=120&q=steve` will return the iq value instead of the q value. – spb Oct 28 '11 at 20:30
  • 1
    @spb, good point! I guess `/(?:\?|&)q=([^&]*)/` would be more robust. – James Oct 30 '11 at 16:11
1
var myURL = 'http://www.example.com/index.php?q=test&=Go'; 

    function gup( name ) //stands for get url param
        {
          name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
          var regexS = "[\\?&]"+name+"=([^&#]*)";
          var regex = new RegExp( regexS );
          var results = regex.exec( myURL );
          if( results == null )
            return "";
          else
            return results[1];
        }


        var my_param = gup( 'q' );

Here is the jsfiddle

Or you can use jQuery's plugin:

URL Parser JQuery

KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
  • 1
    For an improved version of this function, see http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery/5158301#5158301 – James Mar 03 '11 at 02:54
0

If you just want the value of the first term, then:

function getFirstSeachValue() {
  var s = window.location.search.split('&');
  return s[0].split('=')[1];
}

If you want the value of the 'q' term, regardless of where it is in the search string, then the following returns the value of the passed term or null if the term isn't in the search string:

function getSearchValue(value) {
  var a = window.location.search.replace(/^\?/,'').split('&');
  var re = new RegExp('^' + value + '=');
  var i = a.length;
  while (i--) {
    if (re.test(a[i])) return a[i].split('=')[1];
  }
  return null;
}

Both are just examples of course and should test results along the way to prevent unexpected errors.

-- 
Rob
RobG
  • 142,382
  • 31
  • 172
  • 209