for div where background-image url is equal to url or where img src url is equal to url, change to different url in javascript

Here's an example code snippet that uses regex to find and replace the specified URLs in all div elements with a matching background-image or img elements with a matching src URL:

index.tsx
// specify the original URL and the new URL you want to replace it with
const originalURL = 'http://example.com/original.jpg';
const newURL = 'http://example.com/new.jpg';

// find all divs with a matching background-image URL and replace it with the new URL
const divsWithMatchingBgImage = document.querySelectorAll(`div[style*="${originalURL}"]`);
divsWithMatchingBgImage.forEach(element => {
  element.style.backgroundImage = `url(${newURL})`;
});

// find all img elements with a matching src URL and replace it with the new URL
const imgsWithMatchingSrc = document.querySelectorAll(`img[src*="${originalURL}"]`);
imgsWithMatchingSrc.forEach(element => {
  element.src = newURL;
});
687 chars
16 lines

Note that this code assumes that the URLs are enclosed in quotes and does not handle cases where the URLs are enclosed in single quotes, or the use of other syntaxes such as url('example.com/picture.png'). In order to handle those cases, you will need to modify the regex appropriately.

gistlibby LogSnag