Find and replace all matching dynamic strings using jquery or javascript -


here body of html:

<body>     <div>_good morning john... _welcometext.</div>     <label> _welcometext </label>     <a href="">_good</a> </body> 

here 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 replaces 1st instance of matched pattern. replacing key dynamic value coming foreach loop, not able use /key/g replace instances. please help.

i not recommend text based operation that

important, 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


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -