Here is html:
<a href="http://site.com/any/different/folders/picture_name.jpg">Go and win</a>
<a href="http://site.com/not/similar/links/some_other_name.png">Go and win</a>
How to add some text after last "/" in href attribute (before picture_name.jpg) of each link?
The script should give something like:
<a href="http://site.com/any/different/folders/user_picture_name.jpg">Go and win</a>
<a href="http://site.com/not/similar/links/user_some_other_name.png">Go and win</a>
Here user_ is added.
Each link is var img_link
There can be any length of the link.
This solution uses regular expressions which are excellent at simple string manipulation such as this:
$('a[href]').each(function() {
var img_link = $(this).attr('href');
$(this).attr('href', img_link.replace(/([^\/]+)$/, "user_$1"));
});
Updated to use img_link as requested by OP.
If you already have the img_link variable and your own each() loop, simply use the one line inside the function, i.e.:
$(this).attr('href', img_link.replace(/([^\/]+)$/, "user_$1"));
So I would think that the best solution would make use of splice and join.
jQuery Example
$("a").each(function(){
var arr = $(this).attr("href").split("/")
arr[arr.length-1] = "_user" + arr[arr.length-1];
$(this).attr("href",arr.join("/"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With