views:

187

answers:

2

So i got this snippet of code:

$(document).ready(function () {
     var replacementDoneIn = $("body").html();
     var regExMatch = /premier(( {1,5}?)?co(mpany)?([ |\.])?)?/ig;
     var replaceWith = "Nikon";
     var resultSet = replacementDoneIn.replace(regExMatch, replaceWith);
     $("body").html(resultSet);
});

which is some what working for me, but it does not cover more robust and complicated scenario.

I would like to expand find/replace capabilities with a help of jQuery. To properly utilize find/replace of the text inside of the body element excluding any html elements and any attributes and their values.

note: Not being completely certain on how jQuery text() function traverses children of the element it is applied on to.

note: as far as i understand i can loop through all elements in html via $("*"), but does that create any issues for such script

so if you could direct me to the right path, it would be greatly appreciated. Links to resources that address this already, your advices, all will work. Because for some reason my head produces only complicated solutions, so I am wondering may be there are simpler approach.

Thank you in advance.

A: 

If I understand your question correctly, using text() will be the way to go. It includes only the text nodes of of an element and any descendents of that element. So doing

(document.body).text();

will get you the text of all elements contained within the body of the document. Using your regular expression against this should achieve what you need.

Russ Cam
Thank you Russ Cam for your input, but CMS actually hit the nail on the head, i had an issue with .text() that messed up my mark up a bit. I didnt articulate it at all as i just figured that issue out after i have posted the question.
GnrlBzik
+1  A: 

Check my answer to this question:

I posted a simple function that traverses text nodes, replacing its content, without affecting the markup or JavaScript connected event handlers.

CMS
thank CMS, although i did not articulate my self very well i guess you got the answer to what i was looking for, because i did have an issue with .text function. thank you so much.
GnrlBzik