Skip to content Skip to sidebar Skip to footer

How Do I Extract "search Term" From Urls?

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

Solution 1:

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

if (m) { 
    alert(m[1]); // => alerts "test"
} 

Solution 2:

var myURL = 'http://www.example.com/index.php?q=test&=Go'; 

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


        var my_param = gup( 'q' );

Here is the jsfiddle

Or you can use jQuery's plugin:

URL Parser JQuery

Solution 3:

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

functiongetFirstSeachValue() {
  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:

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

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

-- 
Rob

Post a Comment for "How Do I Extract "search Term" From Urls?"