7

In JavaScript I have a string containing a DOM fragment. How would I find and replace the src attribute of an image?

I would like to replace the path of all images with a new path but keeping the image name. Not all the paths are the same and can come from various locations. My regular expression skills are poor at best.

For example:

Change

   <img src='path/to/image/name.jpg' />

into 

   <img src='newPath/name.jpg' />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
redsquare
  • 78,161
  • 20
  • 151
  • 159

6 Answers6

12

Took gumbo's answer and added a few more things to improve it:

  • If the input string contains something other than <img> tags that may have a src attribute - this will no longer matches/replace them.

  • The src attribute may be using single or double quotes.

  • The test being case insensitive.

Resulting in:

string.replace(/<img([^>]*)\ssrc=(['"])(?:[^\2\/]*\/)*([^\2]+)\2/gi, "<img$1 src=$2newPath/$3$2");
gnarf
  • 105,192
  • 25
  • 127
  • 161
7

Try this:

str.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='newPath/$1'");
Gumbo
  • 643,351
  • 109
  • 780
  • 844
4

If using raw (non-DOM) data such as HTML in string form, above doesn't match double quote chars. This code may prove useful, too:

root     = serviceURL("file") + "&src=" + encodeURIComponent(root);
// html itself
html     = html.replace(/src=['"](?:[^"'\/]*\/)*([^'"]+)['"]/g, "src='" + root + "/$1'");
Tim Beres
  • 181
  • 3
1
replace(/(.*)\/(.*)/, "newPath/$2");
Xetius
  • 44,755
  • 24
  • 88
  • 123
  • that's odd. It worked when I tried it in this: http://www.regular-expressions.info/javascriptexample.html – Xetius Aug 19 '09 at 08:56
1

The above solutions doesn't work well in my case, where i had to replace all relative path to absolute path before storing it in DB. But here's my solution in case mine work for anyone else. Cheers.

replace(/<img([^>]*)\ssrc=(['"])(\/[^\2*([^\2\s<]+)\2/gi, "<img$1 src=$2" + BaseURL + "$3$2");
jomaint
  • 105
  • 1
  • 9
0

I used these expression in my project, worked like charm, handling all cases like, quote, double quote, multiple image tags in text etc. In Javascript

text.replace(/\<img([^>]*)\ssrc=('|")([^>]*)\2\s([^>]*)\/\>/gi, "<img$1 src=$2newPath/$3$2 $4/>");

In PHP

preg_replace('/\<img([^>]*)\ssrc=(\'|\")([^>]*)\2\s([^>]*)\/\>/', "<img$1 src=$2newPath/$3$2 $4/>",$text);
LNT
  • 876
  • 8
  • 18