复杂的正则表达式模式

时间:2012-05-12 00:42:16

标签: javascript regex

至少对我来说是一个复杂的正则表达式。这是我的字符串:

/wp-content/themes/modern2/timthumb.php?src=http://www.cnn.com/storyimages/4C59D569-7749-F32B.jpg&h=442&w=642&zc=1&s=2

我想要做的是将该字符串中包含的网址更改为我选择的另一个网址即。

http://www.cnn.com/storyimages/4C59D569-7749-F32B.jpg

TO

http://upload.wikimedia.org/wikipedia/commons/2/20/Google-Logo.svg

我无法弄清楚如何在src =和& h =

之间匹配/替换数据的正则表达式

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

可能没有必要使用正则表达式,但是因为你问过......

var str = '/wp-content/themes/modern2/timthumb.php?src=http://www.cnn.com/storyimages/4C59D569-7749-F32B.jpg&h=442&w=642&zc=1&s=2'
var url = 'http://upload.wikimedia.org/wikipedia/commons/2/20/Google-Logo.svg'
str = str.replace(/src=(.*?)&/, 'src=' + url +'&')

输出:

/wp-content/themes/modern2/timthumb.php?src=http://upload.wikimedia.org/wikipedia/commons/2/20/Google-Logo.svg&h=442&w=642&zc=1&s=2

答案 1 :(得分:1)

必须使用正则表达式吗?

function replaceURL(sourceURL, newPart) {
    var beforeSrc = sourceURL.split('?src=')[0];
    var afterH = sourceURL.split('&h=')[1];

    return beforeSrc + '?src=' + newPart + '&h=' + afterH;
}

然后致电

replaceURL(
    '/wp-content/themes/modern2/timthumb.php?src=http://www.cnn.com/storyimages/4C59D569-7749-F32B.jpg&h=442&w=642&zc=1&s=2',
    'http://upload.wikimedia.org/wikipedia/commons/2/20/Google-Logo.svg'
);

请注意,这是有效的,因为在有效的网址中,?src子字符串不会出现在您预期的地方之前,&h也不会出现。{/ p>

答案 2 :(得分:0)

您想使用这样的正则表达式:

src=([^&$]+)

以下是regexpcode个例子。

相关问题