jQuery搜索并替换img src的一部分

时间:2016-05-09 20:26:34

标签: javascript jquery

在每个页面上,我都有一个包含如下图像的精选图片:

<img class="js-image-replace" src="http://www.example.com/category_name/320/89645428_89645427.jpg" />

/320/引用了图片的大小,我希望它是/660/

我如何搜索320并将其替换为660?

我的所有尝试都会覆盖整个字符串。

1 个答案:

答案 0 :(得分:1)

如果您可以保证此值将是您在字符串中遇到的第一组整数,那么您可以使用以下表达式来替换它:

<script>
$(function(){
  $('.js-image-replace').each(function(){
      // Get your image src
      var source = $(this).attr('src');
      // Replace the first set of integers in your URL with 660
      $(this).attr('src',source.replace(/\/\d+\//,'/660/'));
  });
})
</script>

否则,

示例

您可以see a working example of this in action here并输出如下:

enter image description here