如何仅在文件名前替换图片源串的URL地址?
现在,我以$('img').attr('src', add+"slide1.jpg");的方式进行硬编码,但我需要去掉JS部分中的文件名,只更新文件名之前的URL字符串
var add = "https://lamaisonduchien.ca/wp-content/uploads/revslider/home_1/";
$(".button").on("click", function(){
$('img').attr('src', add+"slide1.jpg");
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Update</button><br />
<img src="http://www.dpwts.com/slide1.jpg" alt="Smiley face" height="300" width="300">
<img src="http://www.aseanta.org/images/slide/slide1.jpg" alt="Smiley face" height="300" width="300">
发布于 2017-11-11 00:38:06
您可以使用正则表达式检查jpg或gif等:
从字符串开头开始以一个或多个字符作为扩展名以检查字符串是否与扩展名^
\b
.+
.+
.+jpg匹配
var add = "https://lamaisonduchien.ca/wp-content/uploads/revslider/home_1/";
$(".button").on("click", function(){
$('img').each(function(index, val) {
var src = $(val).attr("src");
var pattern = /^.+(?=.*\b.+\.jpg)/;
$(val).attr("src", src.replace(pattern, add));
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Update</button><br />
<img src="http://www.dpwts.com/slide1.jpg" alt="Smiley face" height="300" width="300">
<img src="http://www.aseanta.org/images/slide/slide1.jpg" alt="Smiley face" height="300" width="300">
然后,您可以使用replace将matches值替换为add变量。
https://stackoverflow.com/questions/47210180
复制相似问题