Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex replacing src content

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

like image 977
Pete Avatar asked Feb 19 '23 09:02

Pete


2 Answers

Use a negative lookahead:

content.replace(/(<img *src=")(?!http:\/\/)(.*?)"/, '$1' + this.websiteUrl + '$2"');
like image 200
Guffa Avatar answered Feb 28 '23 12:02

Guffa


@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

like image 21
Elias Van Ootegem Avatar answered Feb 28 '23 11:02

Elias Van Ootegem