Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace src attribute if path has value

I have some markup that includes images with the following src attribute:

https://url.com/image/img.jpg

I want to replace any image (or href) that contains /image/ in its path. So the result would be:

https://newurl.com/img.jpg

I've tried using:

/src="(?:[^'\/]*\/)*([^']+)"/g

but not sure how to get it to only match /image/ paths, also when I change src to href it doesn't seem to allow me to replace both.

To clarify, I'm parsing plain text that happens to contain html strings. Also, I need to be able to maintain the file name, but replace the host address.

Update: Here's a jsfiddle of what I have so far. Although it works for the src, it's not taking into account the /image/ in the path, also it removes the href.

like image 503
dzm Avatar asked Jan 21 '26 05:01

dzm


1 Answers

Obligatory don't use regex to parse HTML...


Since you are already using JavaScript, you could use the native DOM API to iterate over all of the img elements and update the src attributes:

Array.prototype.map.call(document.querySelectorAll('img'), function(img) {
  img.src = img.src.replace(/\/image\//, '/');
});

But since you clarified that you have a string that contains HTML, you could create a temporary element, insert the string as HTML, replace the src attributes, and then retrieve the updated innerHTML property value.

For example:

var content = `string of content containing random text, some elements, <p>and paragraphs</p> and more text.. <img src="https://url.com/image/img.jpg" /><img src="https://url.com/image/img.jpg" />`;

// Create the temporary DOM element
var temporaryElement = document.createElement('div');
temporaryElement.innerHTML = content;

// Replace the `src` attributes
Array.from(temporaryElement.querySelectorAll('img')).forEach((img) => {
  img.src = img.src.replace(/\/image\//, '/');
});

// Retrieve the updated `innerHTML` property
var updatedContent = temporaryElement.innerHTML;
console.log(updatedContent);
like image 66
Josh Crozier Avatar answered Jan 23 '26 21:01

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!