Search code examples
jqueryreplaceforeachpattern-matchingreplaceall

Find and replace all matching dynamic strings using jquery or javascript


Here is the body of my html:

<body>
    <div>_good morning John... _welcomeText.</div>
    <label> _welcomeText </label>
    <a href="">_good</a>
</body>

Here is my jQuery:

var custom_obj = {};
custom_obj["_welcomeText"] = "Welcome in custom";
custom_obj["_good"] = "Good in custom";

$.each(custom_obj, function(key, value) {
    $('body').text(function(index,text){
        return text.replace(key,value);
    });
});

This code works but it only replaces the 1st instance of matched pattern. As I am replacing the key which is a dynamic value coming from foreach loop, I am not able to use /key/g to replace all the instances. Please help.


Solution

  • I would not recommend a text based operation like that

    Important, It will be very costly

    var custom_obj = {};
    custom_obj["_welcomeText"] = "Welcome in custom";
    custom_obj["_good"] = "Good in custom";
    
    var $contents = $('body *').addBack().contents();
    $.each(custom_obj, function (key, value) {
        var regex = new RegExp(key, 'g');
        $contents.each(function () {
            if (this.nodeType == 3) {
                this.nodeValue = this.nodeValue.replace(regex, value);
            }
        })
    });
    

    Demo: Fiddle