0

So I'm trying to make an a sort of auto correct system in my website, and I want to detect a word and if the word is in the image source, then replace it. In my code I am trying to replace the word "Dunk" with SB Dunk. In the source it says Dunk twice, but it only replaces the first time it uses "Dunk", and then keeps making errors and keeps adding more "SB's" to the "Dunk". Heres my code.

//https://stockx-360.imgix.net//Nike-Dunk-Low/Images/Nike-Dunk-Low/Lv2/img01.jpg?auto=format,compress&w=559&q=90&dpr=2&updated_at=1580325806`.replace('%20', '-')

shoesimg.addEventListener('error', function(){
    if(shoesimg.src.includes('Dunk')){
    const newshoesimg = shoesimg.src.replace(/Dunk/, 'SB Dunk');
    shoesimg.src = newshoesimg;
    }

3 Answers3

0

You can use replaceAll. Following is the example,

let replacedStr = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// replacedStr is "1 xyz 2 xyz 3"

Another way would be to find the indexes of the word dunk and then using for loop replace one-by-one.

Abhishek
  • 6,912
  • 14
  • 59
  • 85
0

Just add 'g' at the end of regular expression:

shoesimg.addEventListener('error', function(){
    if(shoesimg.src.includes('Dunk')){
    const newshoesimg = shoesimg.src.replace(/Dunk/g, 'SB Dunk');
    shoesimg.src = newshoesimg;
    }

https://dmitripavlutin.com/replace-all-string-occurrences-javascript/

AlexGM
  • 1
0

Try String.replaceAll():

const newshoesimg = shoesimg.src.replaceAll('Dunk', 'SB Dunk');
viragoboy
  • 131
  • 1
  • 4