这是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>
Run Code Online (Sandbox Code Playgroud)
如何添加一些文字去年之后"/"
的href
属性(之前picture_name.jpg
的各个环节)?
脚本应该给出类似的东西:
<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>
Run Code Online (Sandbox Code Playgroud)
这user_
是补充.
每个链接都是 var img_link
可以有任何长度的链接.
此解决方案使用正则表达式,这对于简单的字符串操作非常有用,例如:
$('a[href]').each(function() {
var img_link = $(this).attr('href');
$(this).attr('href', img_link.replace(/([^\/]+)$/, "user_$1"));
});
Run Code Online (Sandbox Code Playgroud)
更新以img_link
按OP的要求使用.
如果您已经拥有img_link
变量和自己的each()
循环,只需使用函数内的一行,即:
$(this).attr('href', img_link.replace(/([^\/]+)$/, "user_$1"));
Run Code Online (Sandbox Code Playgroud)