admin管理员组

文章数量:1403452

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

a) ;sort=score
b) ;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

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

a) http://myserver./search?q=bread?topic=14&sort=score
b) http://myserver./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

Share Improve this question asked May 13, 2011 at 17:36 SatishSatish 6,4858 gold badges44 silver badges63 bronze badges 1
  • this question may help u : stackoverflow./questions/901115/… – xkeshav Commented May 13, 2011 at 17:46
Add a ment  | 

4 Answers 4

Reset to default 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./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./plugin-tags/array-remove-duplicates

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

var str = 'http://myserver./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].

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).

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];

本文标签: JqueryJavascript remove duplicate parameters in a url stringStack Overflow