0

Im trying to get the last string from a URL for example...

http://www.mywebsite/blog/this-post

I want to use jQuery to get 'this-post' Ive the following...

$('img.gigthumb').each(function(){
    var foo = $(this).parent().attr('href').split('/');
    $(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[1]+'.jpg');
})

only it doesn't work and I presume thats because I have multiple '/' within the URL, any idea how to target just the last?

Hope this makes sense!

2

5 Answers 5

5

This is precisely what .pop() is made for:

$('img.gigthumb').each(function(){
    var foo = $(this).parent().attr('href').split('/').pop();
    $(this).attr('src','/lic/wp-content/uploads/2012/01/' + foo + '.jpg');
});
Sign up to request clarification or add additional context in comments.

6 Comments

I have my doubts about using .pop() instead of just foo[foo.length-1]
@ajax333221 - Care to share with the class?
@JosephSilber , I am not English speaker, I googgled what you said and still don't know what you meant. Please say it in other words
@ajax333221 - Why do you have your doubts? What's wrong with using .pop()? Why is foo[foo.length-1] better than .pop()?
@JosephSilber , .pop() it is doing unnecessary work by removing the last item on the array, while arr[arr.lenght-1] isn't. I compared the performance here jsperf.com/pop-vs-arr-length-1
|
1

Don't use the element with index 1 of foo, but the last one:

$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[foo.length-1]+'.jpg');

Comments

1

Splitting with "/" will give you the array:

foo[0] = "http:"
foo[1] = ""
foo[2] = "www.mywebsite"
foo[3] = "blog"
foo[4] = "this-post"

If you want to get the last item regardless of the size of the array do:

foo[foo.length - 1]

or as Joseph mentioned: foo.pop()

1 Comment

+1 .pop() is slower because it is modifying the array (by removing the last item). here are is the proof jsperf.com/pop-vs-arr-length-1
0

Following your example you need the last part of the splits:

$('img.gigthumb').each(function(){
    var foo = $(this).parent().attr('href').split('/');
    var last = foo.length - 1;
    $(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[last]+'.jpg');
})

Comments

0
var foo = $(this).parent().attr('href').replace(/^.*\\/, '');

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.