Search code examples
jqueryjquery-ui-dialog

.replace() only working once for multiple instances of text


I have a JQuery UI dialog that presents changes that were made to inputs on a form submit. I'm wanting the word 'New' to be a different color, but it only changes the first occurrence.

Why does the replace() function work for my line breaks, but not for the css change?

enter image description here

 var i;
        for(i = 0; i < changed_arr.length; i++) {

            var oldValue = changed_arr[i].oldValue;
            var newValue = changed_arr[i].newValue;
            str += changed_arr[i].key + ":  Old - " + oldValue + ", New - " + newValue + "\n";
        }
        error_text = $('#dialog_confirm p').text("Please confirm your update\nbefore proceeding.\n\nChanges for <?= $edit_domain;?>: \n\n" + str);
        //The new line works multiple times, but not the css change
        error_text.html(error_text.html().replace(/\n/g, '<br/>').replace('New', '<span style="color:yellow;">New</span>'));

        $('#dialog_confirm').dialog('open');
    }

Solution

  • You need to include the g (global) and possibly the m (multi-line) modifier(s) for "New":

    replace(/New/gm, '<span style="color:yellow;">New</span>')
    

    It should replace all occurrences similarly to your line break.

    Example:

    https://regex101.com/r/Gsv6hc/1