user3237558
user3237558

Reputation: 61

Replace image source with RegExp where another attribute comes first

I have this for exapmple

<img style="height:375; width:500;" src="../img/ris1_1.jpg" ALIGN="center">
<img src="img/ris1_2.jpg" style="height:375; width:500;" ALIGN="center">

I used this RegExp to replace src tag:

(?<=(<img src=['"]))[^"']+

But it finds only imgs where src comes right after

Also I need to replace only relative paths, not absolute. So if I have absolute path in src I must not replace it.

P.S. Yeah! I've done, thanks Shomz for that! Just do this:

tag.replace(/(img[^>]*src=['"])+(?!http:\/\/)\s*([^'"]*)/gi,"$1http://mydomain.com/$2");

Upvotes: 1

Views: 1479

Answers (2)

Shomz
Shomz

Reputation: 37701

If tag is your tag, you can do:

tag.replace(/(img[^>]*src=['"])+(\s*)[^'"]*/g, '$1REPLACED.jpg');

UPDATE

To omit absolute urls, use this regex (img[^>]*src=['"])+(?!http:\/\/)\s*[^'"]*.

Upvotes: 1

Mofi
Mofi

Reputation: 49096

Instead of just selecting with the search string only the value of src attribute of an img element, use the capturing search string (<img.*?src=['"])[^"']+ and start the replace string with \1 to keep everything from <img to " or ' on replace.

Of course you could simply use search string (?<=src=['"])[^"']+ if the src attribute is not used in any other element than img.

The suggestion by Tony is also good. With searching for (<img)(.+?)( src=["'][^"']+["']) and using as replace string \1\3\2 it is possible to first standardize all img elements by moving src attribute to first position after <img.

Upvotes: 0

Related Questions