我想分割一个attribute
在最后一次出现字符时,添加一个字符串并将数组重新连接在一起。这是一个简化的demo https://jsfiddle.net/Ldjoqtk1/1/.
在演示中我想拆分src
最后一次出现的属性.
然后添加-fx
to the src
path.
原来的src
属性
src="extension.jpg"
src="ext.ension.jpg"
我希望得到什么
src="extension-fx.jpg"
src="ext.ension-fx.jpg"
更具体地说,问题是如果我split('.')
并且该路径有多个.
出现问题(-fx
未正确添加)。
$('img').each(function(){
var a = $(this).attr('src');
var b = a.split('.')
var c = b[0] + '-fx' + '.' + b[1];
console.log(c);
$(this).attr('src', c);
});
img {
height: 100px;
width: 100px;
background: red;
}
img[src*="-fx.jpg"] {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="extension.jpg">
<img src="ext.ension.jpg">
您可以使用.attr( attributeName, function ) http://api.jquery.com/attr/#attr-attributeName-function使用回调函数来更新各个元素的属性值。添加字符串-fx
在 src 属性中,String#lastIndexOf https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf and String#substring https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring可以使用。
// Get the src attribute value of image one by one
$('img').attr('src', function(i, src) {
// Get the index of the last .
var lastIndex = src.lastIndexOf('.');
// Add the string before the last .
// Return updated string, this will update the src attribute value
return src.substr(0, lastIndex) + '-fx' + src.substr(lastIndex);
});
img {
height: 100px;
width: 100px;
background: red;
}
img[src$="-fx.jpg"] {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="extension.jpg" />
<img src="ext.ension.jpg" />
Note:使用的选择器img[src*="-fx.jpg"]
将选择所有图像src
属性值在任何地方都包含给定的字符串。选择图像src
值以给定字符串结尾,使用$=
选择器。
img[src$="-fx.jpg"]
^
如果你想使用正则表达式,可以使用以下正则表达式。
(\.(?:jpe?g|png|gif))$/
Demo https://regex101.com/r/cC8nI7/2
// Get the src attribute value of image one by one
$('img').attr('src', function(i, src) {
return src.replace(/(\.(?:jpe?g|png|gif))$/, "-fx$1");
});
img {
height: 100px;
width: 100px;
background: red;
}
img[src$="-fx.jpg"] {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="extension.jpg" />
<img src="ext.ension.jpg" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)