Jquery在图像src url中的最后一次斜杠后找到替换文本

时间:2016-05-20 07:05:24

标签: jquery image

我知道我在这里发布的问题是愚蠢的,但经过几个小时的谷歌搜索并尝试了所有的一切,我无法得到理想的结果。所以,让我在这里分享,希望在这里得到解决。

我的问题是,我是一个图片网址来源,我需要每次都用新的图片名称更改图片名称。 我发布了我尝试过的代码:

$(function () {
     //Old Image Url where i need to change 32_Penguins.jpg with new file name
     var ImageSrcUrl="../Upload\UserProfile\32_Penguins.jpg"; //Don't change forward slash with backword slash here and then try to answer
     var NewFileName="Tullips.jpg";

     //I tried to replace everything after the last "\"[slash]
     ImageSrcUrl= ImageSrcUrl.replace(/.*$/i, NewFileName); 

     alert(ImageSrcUrl);
});

注意:请不要尝试用反斜杠替换正斜杠然后回答它[Bcoz它可以工作但转换应该通过jquery代码而不是手动完成]

5 个答案:

答案 0 :(得分:1)



$(function() {
      //Old Image Url where i need to change 32_Penguins.jpg with new file name
      var ImageSrcUrl = "../Upload\\UserProfile\\32_Penguins.jpg";
      var index = ImageSrcUrl.lastIndexOf("\\") + 1;
     var path = ImageSrcUrl.substr(0,index);
     var NewFileName="Tullips.jpg ";
     ImageSrcUrl= path+NewFileName; 
     alert(ImageSrcUrl);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$(function(){
     var ImageSrcUrl = "../Upload/UserProfile/32_Penguins.jpg";

     var NewFileName = "Tullips.jpg";
     var index = ImageSrcUrl.lastIndexOf("/") + 1;
     var filename = ImageSrcUrl.substr(index);
     ImageSrcUrl = ImageSrcUrl.replace(filename, NewFileName); 
     alert(ImageSrcUrl);
});

答案 2 :(得分:0)

$(function () {
     //Old Image Url where i need to change 32_Penguins.jpg with new file name
     var ImageSrcUrl="../Upload/UserProfile/32_Penguins.jpg";
     var NewFileName="Tullips.jpg";

     var parts = ImageSrcUrl.split('/');

     parts[parts.length -1] = NewFileName;
     alert(parts.join('/'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 3 :(得分:0)

**I wrote an example for this one:**

$(function () {
    var str = "ss/ll/Test.jpg";
      var m = /[^/]*$/.exec(str)[0];
      var sts = str.replace (m, "Tst.jpg");
      display("Input: " + str);
      display("Replaced: " + sts);

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = msg;
        document.body.appendChild(p);
      }
    });

答案 4 :(得分:0)

我修改了你的初始功能:

function aa() {
    var ImageSrcUrl="../Upload/UserProfile/32_Penguins.jpg";
    var NewFileName="Tullips.jpg";
    ImageSrcUrl = ImageSrcUrl.replace(/[A-z0-9.]*$/i, NewFileName); 
    return ImageSrcUrl;
};

根据我的测试,它应该有用。