jQuery - update image url only folder

52 Views Asked by At

How can I update, Image URL only some part of it...

For Eg: I have 2 folders, if images coming from lenovo folder, I want change that folder to samsung

<img src="images/lenovo/abc.jpg"> to <img src="images/samsung/abc.jpg">

3

There are 3 best solutions below

3
yjs On BEST ANSWER

$(function() {
$("img").each(function() {
var imgURL = $(this).attr('src');
if(imgURL.lastIndexOf('/')>6) {
imgURL = imgURL.replace("images/lenovo","images/samsung");
}
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<img src="images/lenovo/abc.jpg"><img src="images/xyz.jpg">

1
Ibrahim Khan On

Take the current src of img and the use replace() to replace to update src. You can do it like below. Hope this will help you.

$(function () {
    var img = $("img");

    img.each(function () {
        var src = $(this).attr('src');

        if (src.indexOf('lenovo/') > -1) {
            $(this).attr('src', src.replace("lenovo", "samsung"));
        }
    });
})
0
user5697726 On

Check if the src-attribute contains 'lenovo'.

If it does, then replace it.

$(function() {
  var src = $('img:first').attr('src');
  var needle = 'lenovo';
  var altDirectory = 'samsung';
  var rep;

  if (src.search(needle) > -1) {
    rep = src.replace(needle, altDirectory);

    $('img:first').attr('src', rep);
  }       
});

Live-Demo: http://codepen.io/mizech/pen/QyNJEp