8

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' />
0

6 Answers 6

13

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");
Sign up to request clarification or add additional context in comments.

Comments

7

Try this:

str.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='newPath/$1'");

5 Comments

It will do. You need to use "src='newPath/$2'" as the replacement
Editted the answer to fix this
Ah, this works for one image but will not match all images. Is this possible
@redsquare: Just forgot a quantifier and the global flag. And the $1 is correct.
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'");

1 Comment

Much better solution
1
replace(/(.*)\/(.*)/, "newPath/$2");

1 Comment

that's odd. It worked when I tried it in this: regular-expressions.info/javascriptexample.html
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");

Comments

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.