如果url为.jpg,.png&,如何自动替换Scr.js使用js脚本

how auto Replace Scr if url with .jpg,.png & .js use js script

本文关键字:js 替换 何自动 Scr 脚本 使用 amp url jpg png 如果      更新时间:2023-09-26

如果url为.jpg、.png&,如何自动替换Scr。js对于Ex在我的主页上有一些图片链接<img src="http://www.lx5.in/img/img.png"/>自动转换为<img src="http://www.lx5.in.cdn.com/img/img.png"/>可以使用任何.js脚本吗?感谢

这是解决问题的一种相对简单的方法:

function changeSrc (img) {
    // the file types you indicate you wanted to base the action upon:
    var fileTypes = ['png','jpg'],
        // gets the 'src' property from the current 'img' element:
        src = img.src,
        /* finds the extension, by splitting the 'src' by '/' characters,
           taking the last element, splitting that last string on the '.' character
           and taking the last element of that resulting array:
        */
        ext = src.split('/').pop().split('.').pop();
    // if that 'ext' variable exists (is not undefined/null):
    if (ext) {
        // iterates over the entries in the 'fileTypes' array:
        for (var i = 0, len = fileTypes.length; i < len; i++){
            /* if the 'ext' is exactly equal (be aware of capitalisation)
               to the current entry from the 'fileTypes' array:
            */
            if (ext === fileTypes[i]) {
                // finds the '.in/' string, replaces that with '.in.cdn.com/':
                img.src = src.replace(/.in'//,'.in.cdn.com/');
            }
        }
    }
}
// gets all the 'img' elements from the document:
var images = document.getElementsByTagName('img');
// iterates over all those images:
for (var i = 0, len = images.length; i < len; i++){
    // calls the function, supplying the 'img' element:
    changeSrc(images[i]);
}

JS Fiddle演示。

参考文献:

  • Array.pop()
  • document.getElementsByTagName()
  • String.replace()
  • String.split()