Home > database >  JQuery replace find and replace a certain tag in image src
JQuery replace find and replace a certain tag in image src

Time:11-20

I have an html image like below:

<img class="post-thumb" src="https://1.bp.blogspot.com/-v4ekzlZEc/YZUZJjVN8tI/AAAAAAAChsA/GSOuME5yUYs_-G3OX1TfwCPcBGAsYHg/s72-w640-h426-c/402.JPG">

I want to use JQuery to dynamically change anythig that says "/s72-" with "/s720-"

I have the following code, but my regex in the replace is just wrong as I got that from somehwere online.

$(document).ready(function(){
var dimension = 720;
var image = $('.post-thumb');
image.attr({src : image.attr('src').replace(/w\B\d{2,4}/,'w'   dimension)});
});

CodePudding user response:

You can simply use the following regex to replace the fixed character,

/g - will replace more than one occurrence

$(document).ready(function(){
  var dimension = 720;
  var image = $('.post-thumb');
  image.attr({src : image.attr('src').replace(/\/s2-/g, '/s' dimension));
});

Using Native JavaScript:

You don't need jQuery. You can write this in native JS way,

var dimension = 720;
var image = document.querySelector('.post-thumb');
if (image) {
    image.setAttribute('src', image.getAttribute('src').replace('s72', 's'   dimension))
    console.log(image.getAttribute('src'));
}

If you want code to execute on page load use onload or domcontentloaded events.

CodePudding user response:

Why don't use directly replace with 's72' like:

$(document).ready(function() {
  var dimension = 720;
  var image = $('.post-thumb');
  image.attr({
    src: image.attr('src').replace('/s72', '/s'   dimension)
  });
  console.log(image.attr('src'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="post-thumb" src="https://1.bp.blogspot.com/-v4ekzlZEc/YZUZJjVN8tI/AAAAAAAChsA/GSOuME5yUYs_-G3OX1TfwCPcBGAsYHg/s72-w640-h426-c/402.JPG">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>


PS: I only considered one instance to modify, if there should be more to modify use replaceAll

$(document).ready(function() {
  var dimension = 720;
  var image = $('.post-thumb');
  image.attr({
    src: image.attr('src').replaceAll('/s72', '/s'   dimension)
  });
  console.log(image.attr('src'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="post-thumb" src="https://1.bp.blogspot.com/s72-v4ekzlZEc/YZUZJjVN8tI/AAAAAAAChsA/GSOuME5yUYs_-G3OX1TfwCPcBGAsYHg/s72-w640-h426-c/402.JPG">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Reference:

  • Related