1

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");
5
  • 2
    Instead of using a regex why not just select the element and update its .src property Commented Jan 26, 2014 at 13:34
  • Move the src attribute after the img tag in the first one? Commented Jan 26, 2014 at 13:34
  • 1
    I can't replace src with .src because I search it in text, parsed from page. Also I can't move src attribute. Commented Jan 26, 2014 at 13:39
  • (?<=(<img[^>]*src=['"]))[^"']+ is not working( Commented Jan 26, 2014 at 13:54
  • JS regex supports lookbehinds? Commented Jan 26, 2014 at 13:55

2 Answers 2

1

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*[^'"]*.

Sign up to request clarification or add additional context in comments.

3 Comments

It's very good solution! And how to replace only relative paths?
Thank you! It is working! :) But I still can't add old src, such as "img/ris1.jpg" to replacement...
You're welcome! Also, you might need to take care of ../ in the relative paths if you're just switching domains.
0

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.

Comments

Your Answer

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