简体   繁体   中英

jQuery - update image url only folder

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">

 $(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"> 

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"));
        }
    });
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM