JSFiddle - React, Tailwind, and code Playground

by minitech

HTML

<div id="test1"><i>Indiscriminate replace</i></div>
<div id="test2"><i>Specialized replace</i></div>

JavaScript

$("#test1").html(function(i, v) {  
     return v.replace(/i/gi, 'b'); 
});

function toArray(obj) {
    var r = [];

    for(var i = 0; i < obj.length; i++) {
        r.push(obj[i]);
    }

    return r;
}

$('#test2').each(function() {
    var stack = [this];
    var c, n;

    while(c = stack.pop()) {
        var childNodes = toArray(c.childNodes);

        for(var i = 0; n = childNodes[i]; i++) {
            if(n.nodeType === 1) {
                stack.push(n);
            } else if(n.nodeType === 3) {
                var matches = n.nodeValue.split(/(i)/i);

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

                    if(/i/i.test(matches[i])) {
                        newNode = document.createTextNode('b');
                    } else {
                        newNode = document.createTextNode(matches[i]);
                    }

                    n.parentNode.insertBefore(newNode, n);
                }

                n.parentNode.removeChild(n);
            }
        }
    }
});