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

1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

The code you provided will get the first q=, not the last q=.
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].

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.