如果url为.jpg,.png&,如何自动替换Scr.js使用js脚本
how auto Replace Scr if url with .jpg,.png & .js use js script
如果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()
相关文章:
- 如何使用动能js替换画布中的图像
- 简单的js替换并返回文本
- 历史.js替换了错误的内容
- 香草 js 替换 jQuery 的 index() 和 eq()
- 下划线 js 替换对象中的项目
- 有没有更聪明的方法来做这个CSS列JS替换
- 下划线.js:替换集合中的项目
- 反应.js 替换 img src onerror
- 使用kinetic.js替换HTML5画布中的图像
- JS 替换返回原始字符串
- 什么'是HTML中框架集的最佳JS替换
- Js替换和Regex排除一个单词
- JS-替换语言
- D3.js替换段落中的文本
- JavaScript原型.js替换
- 通过CSS或JS替换跨度内的文本
- 如何在所有元素上用“js”替换“no js”类名
- JS替换不起作用
- Regex Js替换Img属性
- JS替换正则表达式,但在输出中使用部分表达式,如变量