A function to match (with regular expressions) and replace DOM text. Deals with nodes individually and works with cross-element-boundary matches!
Switch branches/tags
Nothing to show
Pull request Compare This branch is 50 commits behind padolsey:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
test
demo.html
readme.md

readme.md

See the demo

findAndReplaceDOMText searches for regular expression matches in a DOM node and wraps all matches (and portions of matches separated by node bounderies) with a specified element.

For example:

<p id="t">
	123 456 999
</p>
findAndReplaceDOMText(/9+/, document.getElementById('t'), 'em');

This would result in:

<p id="t">
	123 456 <em>999</em>
</p>

And it also works when matches are spread across multiple nodes! E.g.

<p id="t">
	123 456 99<span>9 foo</span>
</p>
findAndReplaceDOMText(/9+/, document.getElementById('t'), 'em');

This would result in:

<p id="t">
	123 456 <em>99</em><span><em>9</em> foo</span>
</p>

The EM element has been added twice, to cover both portions of the match.

Documentation

It's pretty simple. findAndReplaceDOMText has the following argument signature:

findAndReplaceDOMText(
  regex,       // (RegExp) The regular expression to match
  element,     // (Element) The element to search within
  replacement, // (String|Node|Function) Explained below
  captureGroup // (Number) OPTIONAL: The regex capture group to replace
);

The third argument to findAndReplaceDOMText can be one of:

  • A nodeName (e.g. "em" or "span")
  • A "stencil" node that will be cloned.
  • A function which will return an element whenever called with a match portion (text)

E.g. if I wanted to replace every instance of foo in an element with <span class="found"> I would simply do:

var span = document.createElement('span');
span.className = 'found';
findAndReplaceDOMText(/foo/g, myElement, span);

Changelog

  • 0.1: Initial commit + Fix for IE's broken HTML5 cloneNode (pull request)
  • 0.11: Minor fix: Make sure replacement node function is called in order of matches (see issue #4)
  • 0.2: Fix case where regular expression contains word bounderies and add support for specifying a capture group to replace as the fourth argument to findAndReplaceDOMText() (see issue #5)