替换所有图像的图像源 [英] Replace images source for all images

查看:185
本文介绍了替换所有图像的图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Greasemonkey脚本替换匹配正则表达式的所有图像的 src 属性。
示例:

I want to replace the src attribute for all images matching a regex using Greasemonkey scripting. Example:

替换 http://aff.kooora.com/i/z3.gif

使用 http://example.com/aff.kooora.com/i/z3.gif

我没有编写脚本的经验,但这就是我想出的:

I have no experience in scripting but this is what I came up with:

var allImg=document.getElementsByTagName("img"), i=0, img;
var pattern = aff\.kooora\.com/([A-Za-z0-9/._]*);
while(img=allImg[i++])
{
    result = pattern.exec(img);
    if (result!=null) 
        img.src=img.src.replace(result, 'http://example.com/' + result);
}

它不起作用。

推荐答案

你的正则表达式是问题,你需要用斜杠包装它(否则解释器不知道它应该把它当作正则表达式):

Your regular expression is the problem, you need to wrap it in slashes (otherwise the interpreter has no clue that it should treat that as a regexp):

var allImg=document.getElementsByTagName("img"), i=0, img;

var pattern = /^http\:\/\/aff\.kooora\.com\/(.*)$/;

while (img = allImg[i++])
{
    if (img.src.match(pattern)) {
        img.src = img.src.replace(pattern, 'http://example.com/aff.kooora.com/$1');
    }
}

这篇关于替换所有图像的图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆