0

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
  • I realize that you ask for using "array keys", but your code mixes up objects and array literals. Is that just PHP terminology for "associative arrays", which would be objects in JavaScript, or do you really want to use normal arrays, which would be indexed by number, not with "keys"? Commented Dec 8, 2008 at 9:09
  • Yeah, I have more proficiency in PHP and often get the two mixed up (they do share some common elements, after all). Commented Dec 8, 2008 at 19:22

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.