4

Here's my url string, I am trying to break down the parameters and get the value for "q" parameter.

a) http://myserver.com/search?q=bread?topic=14&sort=score
b) http://myserver.com/search?q=bread?topic=14&sort=score&q=cheese

how do i use Jquery/JavaScript to get "q" value?

for case a), i can use string split or use jquery getUrlParam to get q value = bread

for case b), when there are duplicates how do i retrieve the q value at the end, when there are multiple "q" params

Satish
  • 6,457
  • 8
  • 43
  • 63
  • this question may help u : http://stackoverflow.com/questions/901115/get-querystring-values-in-javascript – xkeshav May 13 '11 at 17:46

4 Answers4

2

in pure javascript, try

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

Reference

in jQuery see this plugin

https://github.com/allmarkedup/jQuery-URL-Parser

UPDATE

when u get array of all query string then to remove duplicate from an array via jQuery try unique or see this plugin

http://plugins.jquery.com/plugin-tags/array-remove-duplicates

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
1

Here you can use a regular expression. For example, we might have this string:

var str = 'http://myserver.com/search?q=bread&topic=14&sort=score&q=cheese';

Find the search portion of the URL by stripping everything from the beginning to the first question mark.

var search = str.replace(/^[^?]+\?/, '');

Set up a pattern to capture all q=something.

var pattern = /(^|&)q=([^&]*)/g;
var q = [], match;

And then execute the pattern.

while ((match = pattern.exec(search))) {
    q.push(match[2]);
}

After that, q will contain all the q parameters. In this case, [ "bread", "cheese" ].

Then you can use any of q.

If you only care about the last one, you can replace the q.push line with q = match[2].

Thai
  • 10,746
  • 2
  • 45
  • 57
0

It looks like you can use getUrlParam for both, but you have to handle the second case's return value as an array with multiple values (at least in the getUrlParam code I'm looking at).

Briguy37
  • 8,342
  • 3
  • 33
  • 53
0

getUrlParam('q') should return an array. Try to get those values with this code:

values = $.getUrlParam('q');

// use the following code
first_q_value = values[0];
second_q_value = values[1];
bitfox
  • 2,281
  • 1
  • 18
  • 17