views:

120

answers:

1

I have a HTML page with which I want to do some client side replacement using Javascript. The values I would like to replace are in an array like so:

var searchFor = new Object();
var replaceWith = new Object();
searchFor =
[
 "quick",
 "brown",
 "fox",
];

replaceWith =
[
 "nimble",
 "black",
 "cat",
];

So every instance of 'brown' should be replaced by 'black'. What's the easiest way to do this that works cross browser?

+2  A: 

I would recurse into all nodes of the DOM using default W3C DOM traversal, picking the text nodes only for processing:

// replacer object, containing strings and their replacements
var replacer = {
  "quick": "nimble",
  "brown": "black",
  "fox": "cat"
};

// prepare regex cache
var replacer_re = (function ()
  {
    var replacer_re = {};
    // certain characters are special to regex, they must be escaped
    var re_specials = /[][/.*+?|(){}\\\\]/g; 
    var word;
    for (word in replacer)
    {
      var escaped_word = word.replace(re_specials, "\\\1");
      // add \b word boundary anchors to do whole-word replacing only
      replacer_re[word] = new RegExp("\\b" + escaped_word + "\\b", "g");
    }
    return replacer_re;
  }
)();

// replace function
function ReplaceText(text)
{
  var word;
  for (word in replacer)
    text = text.replace(replacer_re[word], replacer[word]);
  return text;
}

// DOM recursing function
function ReplaceTextRecursive(element)
{
  if (element.childNodes)
  {
    var children = element.childNodes;
    for (var i = children.length - 1; i >= 0; i--)
      ReplaceTextRecursive(children[i]);
  }    

  if (element.nodeType == 3) // 3 == TEXT_NODE
    element.nodeValue = ReplaceText(element.nodeValue);
}

// test it
function test()
{
  ReplaceTextRecursive(document)
}
Tomalak
An associative array makes much more sense. Thanks very much, you're a star. :)
different