views:

48

answers:

5
+1  Q: 

jQuery cut link

Here is html:

<a href="http://site.com/any/different/folders/picture_name.jpg"&gt;Go and win</a>
<a href="http://site.com/not/similar/links/some_other_name.png"&gt;Go and win</a>

How to cut all the data from a href, except picture_name.jpg? There can be any length of the link, we must take just the value from last / to last "

And anybody does know the shortest way to compare, if alt and title of current link are equal?

Thanks.

+2  A: 

Once you grab the a element with getElementsByTagName or getElementById:

var parts = element.href.split('/')
last_part = parts[parts.length-1]
Aaron Harun
`parts.pop()` will work too, or `split('/').pop()` for just the last part. don't forget your semi-colons :-)
Andy E
+5  A: 

If you want to actually change the href to picture_name.jpg and some_other_name.png respectively, you can pass a function to .attr() and use .lastIndexOf()/.substring(), like this:

$("a").attr('href', function(i, href) {
  return href.substring(href.lastIndexOf('/') + 1);
});

You can view/play with a quick demo here


Alternatively if you're using a .each() you can get/use the value like this:

$("a").each(function() {
  var new_href = this.href.substring(this.href.lastIndexOf('/') + 1);
  //use it, e.g.: alert(new_href);
});​

You can see a demo of that here

Nick Craver
I want to throw picture_name.jpg into new variable. var link = ? Can you update?
Happy
@Happy - Can you clarify a bit? Each link would be a different variable, so where do you want this variable to go? Are you doing one link at a time or...?
Nick Craver
I'm using each() -> function
Happy
`var links = [];$("a").attr('href', function(i, href) { links[] = href.substring(href.lastIndexOf('/') + 1);});`
Aaron Harun
var link = $(this).attr('href', function(i, href) {return href.substring(href.lastIndexOf('/') + 1);
Happy
will it work(mine)?
Happy
@Happy - Updated the answer to show a quick way to do that :)
Nick Craver
@Nick Craver - thanks a lot
Happy
+3  A: 
var hrefs = $("a").map( function() {
  return this.href.substring(this.href.lastIndexOf('/')+1);
})

will return an array:

["picture_name.jpg", "some_other_name.png"]

Well, and the other question...

And anybody does know the shortest way to compare, if alt and title of current link are equal?

Sure, just compare them

var currentLink = $("a")[0]; // whatever

if (currentLink.alt == currentLink.title) {
  // some action
} else {
  // some other action
}
Tomalak
The second part of the answer wouldn't ever evaluate to true, `currentLink.alt` would always be undefined, since it's not a valid property/attribute. Short demo here: http://jsfiddle.net/vQPQa/
Nick Craver
+1  A: 
var a = $("#link");
var link = a.href;
alert( link.substr(0, link.lastIndexOf("/")+1) );
alert(a.href == a.title); 
Riateche
+1  A: 

You can also use a regular expression:

var url = element.href.match(/([^\/]*)$/)[1];

elektronaut