Search code examples
javascriptreplacefindcontains

Find and replace word causing duplication


I'm trying to loop through a set of DOM elements/buttons. I then want to find a particular word and replace it with two words.

This works in almost all scenarios.

For example, the following code will change the text of the divs to "APPLES".

    let buttons = document.getElementsByClassName("main-buttons");

    for(var i=0; i<buttons.length; i++) {
        var res = buttons[i].innerHTML.replace(/ORANGE/gi, "APPLES");
        buttons[i].innerHTML = res;
    };

However, I am having a problem, when I want to replace "ORANGE" with "ORANGE BALLOONS".

Instead of seeing the words "ORANGE BALLOONS" in my buttons. I see "ORANGE BALLOONS BALLOONS".

    let buttons = document.getElementsByClassName("main-buttons");

    for(var i=0; i<buttons.length; i++) {
        var res = buttons[i].innerHTML.replace(/ORANGE/gi, "ORANGE BALLOONS");
        buttons[i].innerHTML = res;
    };

I know this has something to do with the regex and my loop catching onto "orange", but I wondered if there was a better way to find and replace in javascript.

Or find a word and add another one next to it.


Solution

  • You can negative lookahead for BALLOONS when matching ORANGE to make sure existing ORANGE BALLOONS doesn't get changed:

    for (const button of document.querySelectorAll('.main-buttons')) {
      button.innerHTML = button.innerHTML.replace(
        /ORANGE(?! BALLOONS)/gi,
        'ORANGE BALLOONS'
      );
    }
    

    If each of these elements contains text only, also change the innerHTML to textContent - better to only use innerHTML with HTML markup. (in the case of plain text, .textContent is more appropriate, faster, and safer)