Skip to content Skip to sidebar Skip to footer

Regular Expression In Javascript - Replace Image Src Attribute

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

Solution 1:

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

Solution 2:

Try this:

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

Solution 3:

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

Solution 4:

replace(/(.*)\/(.*)/, "newPath/$2");

Solution 5:

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

Post a Comment for "Regular Expression In Javascript - Replace Image Src Attribute"