Smart text replacing jQuery

I need to replace part of the text, for example. mustache var {{myvar}}, on an already loaded page. Html example:

<html> <head> <title>{{MYTITLE}}</title> </head> <body> <p><strong><ul><li>text {{TEXT}}</li></ul></strong></p> {{ANOTHER}} </body> </html> 

What is the problem? Use $(html).html(myrenderscript($(html).html())) !

It is ugly, slow and casts <script> tags.

What you need?

I want to get the closest tag with {{}}, and not render and replace.

Your research?

First, I tried: $('html :contains("{{")) . But it returns <title>, <p>, <strong> .... But I need <title> and <li> .

How did I try to filter them:

 $('html :contains("{{")').filter(function (i) { return $(this).find(':contains("{{")').length === 0 }); 

... but this WONT returns {{ANOTHER}} . And this is my dead end. Your suggestions?

+6
source share
3 answers

Using http://benalman.com/projects/jquery-replacetext-plugin/ you can do the following:

 $('html *').replaceText(/{{([^}]+)}}/, function(fullMatch, key) { return key; }, true); 

See http://jsfiddle.net/4nvNy/

+2
source

If all you want to do is replace this text, then of course the following works (or I misunderstood)

used as follows: CONTAINER (body) - replaceTExt (search term (I built a function to always include {{}} around the term), (replace - this will also remove {{}})

 $('body').replaceText("MYTITLE","WHATEVER YOU WANT IT REPLACING WITH"); $.fn.replaceText = function(search, replace, text_only) { return this.each(function(){ var v1, v2, rem = []; $(this).find("*").andSelf().contents().each(function(){ if(this.nodeType === 3) { v1 = this.nodeValue; v2 = v1.replace("{{" + search + "}}", replace ); if(v1!=v2) { if(!text_only && /<.*>/.test(v2)) { $(this).before( v2 ); rem.push(this); } else this.nodeValue = v2; } } }); if(rem.length) $(rem).remove(); }); }; 
+1
source

You can generally avoid jQuery if you want to do something like this:

 <body> <p><strong> <ul> <li>text {{TEXT}}</li> </ul> </strong></p> {{ANOTHER}} <hr/> <div id="showResult"></div> <script> var body = document.getElementsByTagName('body')[0].innerHTML; var startIdx = 0, endIdx = 0, replaceArray = []; var scriptPos = body.indexOf('<script'); while (startIdx != 1) { startIdx = body.indexOf('{{', endIdx) + 2; if(startIdx > scriptPos){ break; } endIdx = body.indexOf('}}', startIdx); var keyText = body.substring(startIdx, endIdx); replaceArray.push({"keyText": keyText, 'startIdx': startIdx, 'endIdx': endIdx}); } document.getElementById("showResult").innerHTML = JSON.stringify(replaceArray); </script> </body> 

Then you can do what you want with replaceArray.

+1
source

All Articles