我想在最后一个字符出现时拆分attribute
,然后添加一个字符串并将数组连接在一起。这是一个简化的demo。
在演示中,我想在src
的最后一次出现时拆分.
属性,然后将-fx
添加到src
路径。
原始的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 )
和回调函数来更新相应元素的属性值。要在src属性中添加字符串-fx
,可以使用String#lastIndexOf
和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" />
注意:使用img[src*="-fx.jpg"]
的选择器将选择src
属性值包含给定字符串的所有图像。要选择src
值以给定字符串结尾的图像,请使用$=
选择器。
img[src$="-fx.jpg"]
^
如果要使用正则表达式,可以使用以下正则表达式。
(\.(?:jpe?g|png|gif))$/
// 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" />
这是你可以通过在javascript中使用lastIndexOf
和'substring'函数来实现的。我刚刚更新了你的小提琴。看看它
lastIndexOf
- >将获得角色.
的位置,然后使用子串函数,您可以加入以获得您想要的结果
$('img').each(function(){
var a = $(this).attr('src');
var pos = a.lastIndexOf('.');
var newchar = a.substring(0,pos)+'-fx';
var replacingchar = newchar+a.substr(pos);
console.log(replacingchar);
});
您可以在最后一次出现时拆分。有:
split = str.match(/(.*)\.(.*)/)
如果实际上至少有一个.
(在RegExp中表示为\.
),结果将是一个数组,其中元素2是最后一个.
之前的所有内容,而元素3是它之后的所有内容。
你可以试试
var k="ext.abc.jpg";
var l= k.substring(0, k.lastIndexOf("."))+"-fx"+k.substring(k.lastIndexOf(".") , k.length);;
console.log(l);
这里我将字符串分为两部分,首先是在.jpg之前的部分,然后在其中添加“-fx”然后添加包括“。”的最后部分;