jQuery 删除 ? 之后的所有字符在img源文件中

标签 jquery regex image replace src

想要修改 img src 来自:

<div class="solo">
  <img src="/uploads/2016/08/Simone-B.jpg?fit=97%2C146&amp;ssl=1">
</div>

致:

<div class="solo">
  <img src="/uploads/2016/08/Simone-B.jpg">
</div>

尝试使用以下但不起作用:

jQuery('.solo img').each(function(){
     jQuery(this).attr('src',jQuery(this).attr('src').replace('?*',''));
});

有什么建议吗?提前致谢

最佳答案

在代码中 .replace('?*','') 替换字符串 ?*。要删除该特定部分,您需要使用正则表达式,例如 .replace(/\?.*/,'')

但更好的方法是使用 attr() 方法,带有基于旧值进行迭代和更新的回调。您可以在哪里使用 String#split 删除属性值中?后面的字符串部分的方法。

jQuery('.solo img').attr('src',function(i,v){
   return v.split('?')[0]; // get the string part before the `?`
   // or 
   // return v.replace(/\?.*/,'');
});

关于jQuery 删除 ? 之后的所有字符在img源文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39375360/

相关文章:

javascript - Jquery ajax 解析具有不同命名数组的 json 文件

python - Python re 中的贪婪匹配与非贪婪匹配

python - 1 或 2 或 3 个十进制数的正则表达式,不允许有前导零,允许精度 2 和分数

python - 使用 Python 捕获单帧(使用网络摄像头)

android - 避开间隙并放置图像

javascript - jquery数据不解析值html5数据自定义属性

jquery - 让 Jquery 在可放置和可拖动的 <div> 中可排序

javascript - jquery中长轮询的有效方法

regex - notepad++正则表达式交换两个值

python - 改变图像的深度?