views:

23

answers:

4

I am trying to grab that 15 at the end of the href with jquery..

 <a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>

Any ideas?

+4  A: 

You don't need jQuery for this, just vanilla JavaScript:

var href = someLinkElement.href;
var lastIndex = href.lastIndexOf('/') + 1;
var lastComponent = href.substring(lastIndex);
Jacob Relkin
+1 for avoiding regex ;-)
Tomalak
Agreed that jQuery is overkill, until you have a list of these things that you want to work with ... then the `$(elements).each(...);` becomes really handy
drachenstern
+2  A: 
var num = $("a.ajax").attr("href").replace(/.*\/(\d+)$/, "$1");

Explanation of the regex:

.*           # anything (this runs right to the end of the string)
\/           # a slash (backtracks to the last slash in the string)
(\d+)        # multiple digits (will be saved to group $1)
$            # end-of-string anchor (ensures correct match)

The replace() call will substitute the entire input string with the number at its end, whatever it might be. It will return "" if there's no number at the end.

Oh, and as added bonus here is something that uses jQuery some more, modify as needed:

$("a.ajax").each(function () {
  $(this).data("num", /* store in data for later re-use */
    $(this).attr("href").replace(/.*\/(\d+)$/, "$1")
  );
});
Tomalak
YOU ARE JEDI. That's now even a documented jQuery method and it works. How is not 'actually replacing anything'?
Trip
@Trip: `attr("href")` returns a string, basically a copy of the attribute value. The `replace()` operates on that copy. To replace the actual `href` value, I'd need to call `attr("href", newValue)`, but that's not happening here.
Tomalak
+1  A: 
$(".ajax").each( function() {
  var lastElementOfHREF = $(this).attr("href").split("/").pop();
  // now you do something here with this lastElement...
});
drachenstern
+2  A: 

You can do it like this:

var Value=$("a.ajax").attr("href").split("/").pop();

It's faster than using regex.

Example in action.

Gert G
since it's a set of galleries I imagine there's going to be a lot of these at a time. Yours only grabs ONE of those. Just thought I would point that out. ~ Also, I like how we both managed to post roughly the same answer at the same time ;)
drachenstern
The OP didn't indicate that there were more than one. I.e. "I am trying to grab that `15` at the end of **the** href".
Gert G
+1 for the `split()`/`pop()` approach. This is somewhat more resource-intensive than doing it with `lastIndexOf()`/`substring()`, but for most UI code this will hardly make any noticeable difference.
Tomalak