0

I'm using treewalker to replace matched words on the current page from an object.

Im' running into one issue where it is replacing a matched word that is the path of an img and not a text node.. any ideas?

var a = finalList;
    var walk = document.createTreeWalker(document, NodeFilter.SHOW_TEXT, null, false), n;

    while(n = walk.nextNode()) {
        //n.nodeValue = n.nodeValue.replace(/foo/g, 'bar');        
        for (var i = 0; i < a.length; i++) {
            var item = a[i];
            var text = item.text;
            var frequency = item.frequency;
            var re = new RegExp(text, 'gi'); 
            replaced = $("body").html().replace(re, frequency);
            $("body").html(replaced);
            console.log(text, " replaced with: ", frequency);
        }
    }

EDIT* finalList looks like:

finalList = {bla: 100, foo: 200, baz: 300} 
ZiNG
  • 89
  • 1
  • 13
  • 1
    This probably isn’t the cause of the ``’s path being affected, but I see another problem in your code. You need to escape `text` before creating a `new RegExp` from it, or else special characters in the text will be interpreted as regexp characters. For example, the search text “[note]” would match the found text “n”. JavaScript [doesn’t come with a `RegExp.escape` function](http://stackoverflow.com/q/3561493/578288), but you could use [`_.escapeRegExp`](https://lodash.com/docs#escapeRegExp) from the [Lodash](https://lodash.com/) library. – Rory O'Kane Apr 17 '16 at 09:22
  • 1
    `a` (`finalList`) is an object, not an array. It does not have a length, and cannot be iterated over in the way that you are trying to do. Instead, iterate over `Object.keys(a)`. Also, you do not want to replace on the entire body. Instead, replace within the current node, so `n.nodeValue = n.nodeValue.replace(re, frequency);`. –  Apr 17 '16 at 10:46

0 Answers0