在最后一个字符处拆分,然后连接。

29

我想要在最后一个字符出现的位置分割一个attribute,然后添加一个字符串并将数组重新拼接。以下是一个简化的演示

在演示中,我想要在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">


你能否添加一个输入字符串和期望的输出示例? - Tushar
@Tushar 在演示中有一个例子,但我也会将其添加到帖子中。 - justinw
为什么不直接按“.jpg”分割,然后再加上“-fx”呢? - l'L'l
因为图片的扩展名可以是.png.gif.jpeg - Tushar
@Tushar:即使如此,一个简单的正则表达式也可以处理这个问题……不过lastIndexOf可能是更好的解决方案。 - l'L'l
4个回答

35
您可以使用回调函数的.attr( attributeName, function )来更新相应元素的属性值。 如果要在src属性中添加字符串-fx,可以使用String#lastIndexOfString#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" />


15

通过在JavaScript中使用lastIndexOfsubstring函数,您可以完成这项任务。 我已经更新了您的fiddle,请查看。

lastIndexOf函数将获取字符.的位置,然后使用substring函数拼接以获取所需的结果。

$('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);

});

JS FIDDLE


8
您可以使用以下方法按最后出现的 "." 进行分割:
split = str.match(/(.*)\.(.*)/)

如果实际上至少有一个 . (在RegExp中标为 \。 ),则结果将是一个数组,其中元素2是最后一个 . 之前的所有内容,而元素3则是它之后的所有内容。

1

你可以尝试像这样

var k="ext.abc.jpg";
var l= k.substring(0, k.lastIndexOf("."))+"-fx"+k.substring(k.lastIndexOf(".") , k.length);;
console.log(l);

这里我将字符串分成两部分,第一部分是在 .jpg 之前的内容,然后在其后添加“-fx”,最后再将包括“.”在内的最后一部分添加进去;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接