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 getUr开发者_JAVA技巧lParam 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
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
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]
.
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];
精彩评论