DOM Find and Replace Utility

0.5.0 · abandoned · verified Sun Apr 19

This utility, `heti-findandreplacedomtext`, is a fork of the original `padolsey/findAndReplaceDOMText` library. Its core function is to search for regular expression matches within a given DOM node and subsequently replace or wrap each match with a specified node or piece of text. A key differentiator is its robust handling of matches that span across multiple DOM nodes, ensuring that all fragmented portions of a match are correctly processed and modified. The `heti-` fork specifically introduced an `offset` option to address and fix issues related to browser support for regex lookbehind, enhancing cross-browser compatibility. The package's current stable version, 0.5.0, was published over six years ago, indicating that active development has ceased and the package is largely unmaintained. It is primarily used for client-side DOM manipulation tasks without notable external runtime dependencies. For TypeScript users, community-maintained type definitions (`@types/findandreplacedomtext`) are available.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates wrapping text with `em` and `strong` tags, including across node boundaries, and replacing text with a custom element and uppercase transformation.

document.body.innerHTML = `
  <p id="t1">
    123 456 Hello
  </p>
  <p id="t2">
    123 456 Hell<span>o Goodbye</span>
  </p>
  <div id="t3">
    This is a test. Another test word.
  </div>
`;

import findAndReplaceDOMText from 'heti-findandreplacedomtext';

console.log('Original DOM content:');
console.log(document.body.innerHTML);

// Example 1: Basic wrap
findAndReplaceDOMText(document.getElementById('t1'), {
  find: /Hello/,
  wrap: 'em'
});

// Example 2: Wrap across multiple nodes
findAndReplaceDOMText(document.getElementById('t2'), {
  find: /Hello/,
  wrap: 'strong'
});

// Example 3: Replace text using a function
findAndReplaceDOMText(document.getElementById('t3'), {
  find: /test/g,
  replace: function(portion, match) {
    const span = document.createElement('span');
    span.style.color = 'blue';
    span.textContent = portion.text.toUpperCase();
    return span;
  }
});

console.log('\nModified DOM content:');
console.log(document.body.innerHTML);

view raw JSON →