Jose Salazar Jose Salazar - 2 months ago 8
jQuery Question

jQuery remove all characters after ? in img src

Would like to modify img src from:

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


To:

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


Tried using the following but not working:

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


Any suggestions? Thanks in advance

Answer

In your code .replace('?*','') replace string ?*. For removing that particular part you need to use regex instead like .replace(/\?.*/,'').

But the better way is to use attr() method with a callback for iterate and update based on the old value. Where you can use String#split method for removing the string part after ? in the attribute value.

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