Javascript 如何从图像路径中删除字符串
我在这段代码中所做的是,无论您想要多少个图像,您所需要的只是将它们作为css类使用path Sub.html:Javascript 如何从图像路径中删除字符串,javascript,jquery,Javascript,Jquery,我在这段代码中所做的是,无论您想要多少个图像,您所需要的只是将它们作为css类使用path Sub.html: <div> <img src ="../images/aa.png" class="path"/> <img src ="../images/bb.png" class="path"/> <img src ="../images/cc.png" class="path"/> <img src ="../images/dd.png"
<div>
<img src ="../images/aa.png" class="path"/>
<img src ="../images/bb.png" class="path"/>
<img src ="../images/cc.png" class="path"/>
<img src ="../images/dd.png" class="path"/>
<img src ="../images/ee.png" class="path"/>
</div>
一切正常,路径正在添加到图像中
URL:localhost:8080/abc/def/ghi/jkl/css/images/aa.png.
但所需的url是localhost:8080/abc/def/css/images/aa.png。
如何从url中删除ghi
和jkl
而jkl
值保持变化,因为ghi
是静态值,每次都是相同的
使用如下正则表达式:
var newSource = replace(/\/ghi\/[^\/]*/, '');
[^\/]
部分匹配除/
之外的所有内容。
这是将/ghi
之后的url变量部分获取到下一个/
所需的
因此,您的代码将变成:
$('#main').load( "../sub.html",function(data){
$.each($('.path'), function(index){
var originalSource = $(this).attr('src');
// Replacing the source
var newSource = originalSource.replace(/\/ghi\/[^\/]*/, '');
// Setting the new value of src
$(this).attr('src', newSource);
});
});
编辑
看这个。我使用了您的代码的简化版本,一切正常。如果您检查图像,您可以看到src属性被替换为它应该被替换的状态。
newSource.replace(/(\/ghi\/jkl)/g')
@adeneo:忘了提一下,jkl值是动态的,它们会不断变化everytime@adeneo例如它不工作。试用代码:var rnewSource=newSource.replace(/(\/ghi |\/jkl)/g';这些图像是用手工制作的吗?它们不是资源吗?使用../../../images/ee.png或images/ee.png。你能描述一下Sub.html在哪个目录下吗?我试过了,但url还是一样,没有删除值。。。例如,如果我们有“ghi-typ”,这行吗?非常感谢兄弟的回答是的,行得通。所有元素都有“path”类吗?我刚刚用小提琴测试了代码,一切正常。你使用这个解决方案成功了吗?
$('#main').load( "../sub.html",function(data){
$.each($('.path'), function(index){
var originalSource = $(this).attr('src');
// Replacing the source
var newSource = originalSource.replace(/\/ghi\/[^\/]*/, '');
// Setting the new value of src
$(this).attr('src', newSource);
});
});