Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery update link

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.

like image 228
Happy Avatar asked Aug 10 '26 16:08

Happy


2 Answers

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"));
like image 120
Senseful Avatar answered Aug 13 '26 07:08

Senseful


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("/"));
});
like image 29
runxc1 Bret Ferrier Avatar answered Aug 13 '26 07:08

runxc1 Bret Ferrier