admin管理员组

文章数量:1322540

I have an image tag with a src and I want to prepend a website url onto the src but only if it doesn't start with http://. so far I have

content.replace(/(<img *src=")(.*?)"/, '$1' + this.websiteUrl + '$2"');

but I don't know how to do the not starting with http:// bit

I have an image tag with a src and I want to prepend a website url onto the src but only if it doesn't start with http://. so far I have

content.replace(/(<img *src=")(.*?)"/, '$1' + this.websiteUrl + '$2"');

but I don't know how to do the not starting with http:// bit

Share Improve this question asked Nov 26, 2012 at 9:53 PetePete 58.5k29 gold badges130 silver badges184 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Use a negative lookahead:

content.replace(/(<img *src=")(?!http:\/\/)(.*?)"/, '$1' + this.websiteUrl + '$2"');

@Guffa's pattern is the answer. Just a couple of side-notes: suppose the markup looks like this <img alt="foo" src="foo/bar.png" />, your pattern won't work, try this:

content.replace(/(<img.+src=")(?!http:\/\/)(.*?)"/,'$1' + this.websiteUrl + '$2"');

And if you're going to use this regex for an entire DOM(fragment), consider using a parser instead of regex, too. Here's a X-browser example

You don't really need a regex if you're just prepending some text. How about just:

if /^http:\/\//.test(img.src)
    img.src = this.websiteUrl + img.src;

Where img is the element you are changing the src attribute for.

If you don't have the img tag or one of it's parents as an object, but your HTML is well formed, you can use a DOMParser to get them:

var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/XML");
var collection = doc.getElementsByTagName("img");
for (var i = 0; i < collection.length, i++){
    if /^http:\/\//.test(collection[i].src)
        collection[i].src = this.websiteUrl + collection[i].src;
}

In my case the solution provided by Elias Van Ootegem didn't work. I'm using:

content.replace(/(<img[^]+?src=")(?!http:\/\/)(.*?)"/gi,'$1' + this.websiteUrl + '$2"');

This one works even if the img tag spread on 2 lines and even with multiple img tags

本文标签: Javascript Regex replacing src contentStack Overflow