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

时间:2013-07-14 17:01:12

标签: javascript replace

如何自动替换Scr,如果网址为.jpg,.png&amp; .js文件 对于前 在我的主页上有一些图像链接 <img src="http://www.lx5.in/img/img.png"/>自动转换为<img src="http://www.lx5.in.cdn.com/img/img.png"/> 是否可以使用任何.js脚本? 感谢

1 个答案:

答案 0 :(得分:1)

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

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 demo

参考文献: