Question

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.

Was it helpful?

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

OTHER TIPS

You should use this syntax to create a regular expression

var myRegex = new RegExp(key, 'g');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top