Reputation: 78667
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' />
Upvotes: 8
Views: 19459
Reputation: 916
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);
Upvotes: 0
Reputation: 105
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");
Upvotes: 1
Reputation: 181
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'");
Upvotes: 4
Reputation: 106332
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");
Upvotes: 13
Reputation: 655219
Try this:
str.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='newPath/$1'");
Upvotes: 7