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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With