4

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

4 Answers 4

5

Use a negative lookahead:

content.replace(/(<img *src=")(?!http:\/\/)(.*?)"/, '$1' + this.websiteUrl + '$2"');
Sign up to request clarification or add additional context in comments.

Comments

3

@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

2 Comments

Thanks elias, that bit with the .+src was very helpful
wow finally someone who figured out that you need a the .+ between img and src! nice work!
0

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;
}

2 Comments

That doesn't really check if the src already begins with http and as it is only text I am scrolling through I don't have the img as an object
@Pete How did you obtain the HTML?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.