tags:

views:

8048

answers:

5

Hi,

I am new to JQuery.

If I have the following tag. What is the best JQuery method to extract the value for "page" from the href.

<a href="Search/Advanced?page=2">2</a>

Malcolm

+4  A: 

Hi!

First of all you need to extract the path with something like this:

$("a#myLink").attr("href");

Then take a look at this plugin: http://plugins.jquery.com/project/query-object

It will help you handle all kinds of querystring things you want to do.

/Peter F

Peter Forss
A: 

Use this jQuery extension by James Padoley

http://james.padolsey.com/javascript/regex-selector-for-jquery/

IainMH
+4  A: 

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a>-tag as you have it, but if you should you can also do

var number = $('a').text();
Kenny Eliasson
Nadia Alramli
Yes, I know about the other arguments, maybe should included that in the answer. But why wouldn't it work with multiple characters?
Kenny Eliasson
The answer does work for multiple characters. In fact I just tested this in Firebug. The single argument to substring is the starting location of the substring, if a second argument is not specified it will just read to the end of the string.Nadia does bring up a good point about multiple arguments, though.
Justin Ethier
A: 

Here's a method that works by transforming the querystring into JSON...

var link = $('a').attr('href');

if (link.indexOf("?") != -1) {
    var query = link.split("?")[1];

    eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");

    if (query.page)
     alert(unescape(query.page));
    else
     alert('No page parameter');

} else {
    alert('No querystring');
}

I'd go with a library like the others suggest though... =)

great_llama
+4  A: 

The first thing that comes to mind for me is a one-liner regex.

var pageNum = $("a#specificLink").attr("href").match(/page=([0-9]+)/)[1];
Matchu