Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a text in html tag without effecting tags attributes and links

I want to replace a specific word in my code without effecting html URLs and attributes. i tried to replace each p tag but there are some contents in div tags which also needs to be replaced.

$("p:not(:has(img))").each(function(){
    var b = $(this).html().replace(/oldtext/g, "newtext");
    $(this).html(b);  
});
like image 470
AHMED.D Avatar asked Nov 01 '22 05:11

AHMED.D


1 Answers

I wrote a vanilla JavaScript function for you, it doesn't change anything but the oldtext to the newtext:

replaceAllTextWith = function (jq, oldtxt, newtxt) {
    for (var j = 0; j < jq.length; j++) {
        var el = jq[j];
        for (var i = 0; i < el.childNodes.length; i++) {
            var cnode = el.childNodes[i];
            if (cnode.nodeType == 3) {
                console.log(el.tagName);
                var nval = cnode.nodeValue;
                //add .toLowerCase() here if you want to consider capital letters
                if (-1 < nval.indexOf(oldtxt)) {
                    cnode.nodeValue = nval.replace(new RegExp(oldtxt, "g"), newtxt);
                }
            } else if (cnode.nodeType == 1) {
                replaceAllTextWith([cnode], oldtxt, newtxt);
            }
        }
    }
};

you can call it like:

replaceAllTextWith($("p:not(:has(img))"), "oldtext", "newtext")
like image 88
Mehran Hatami Avatar answered Nov 15 '22 06:11

Mehran Hatami