views:

732

answers:

3

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' />
+5  A: 

Try this:

str.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='newPath/$1'");
Gumbo
doesnt seem to work. changes 'http://blog.internetnews.com/skerner/smk/testpilot.png' into'http://newPath/blog.internetnews.com/skerner/smk/testpilot.png'
redsquare
It will do. You need to use "src='newPath/$2'" as the replacement
Xetius
Excellent, seems to do the trick, cheers Xetius
redsquare
Editted the answer to fix this
Xetius
Ah, this works for one image but will not match all images. Is this possible
redsquare
@redsquare: Just forgot a quantifier and the global flag. And the `$1` *is* correct.
Gumbo
Ok, got it working. Thanks for your help all
redsquare
+1  A: 
replace(/(.*)\/(.*)/, "newPath/$2");
Xetius
cant get this to work, it ends up with "newPath/>"
redsquare
that's odd. It worked when I tried it in this: http://www.regular-expressions.info/javascriptexample.html
Xetius
see http://pastebin.me/95775a662ddb4f79da1f7beaa1d4749b
redsquare
+1  A: 

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
cheers gnarf .
redsquare