Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
F

findAndReplaceDOMText

> 编程语言
Open source

:mag: Find and replace DOM text

791 stars0 likes0 views
WebsiteGitHub

About

:mag: Find and replace DOM text

findAndReplaceDOMText

See the demo

findAndReplaceDOMText searches for regular expression matches in a given DOM node and replaces or wraps each match with a node or piece of text that you can specify.

For example:

xml

  123 456 Hello
javascript
findAndReplaceDOMText(document.getElementById('t'), {
  find: /Hello/,
  wrap: 'em'
});

This would result in:

xml

  123 456 Hello

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

xml

  123 456 Hello Goodbye
javascript
findAndReplaceDOMText(document.getElementById('t'), {
  find: /Hello/,
  wrap: 'em'
});

This would result in:

xml

  123 456 Hello Goodbye

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

Installation

Grab the latest findAndReplaceDOMText.js (or npm install findandreplacedomtext) and include it as a `` on your page.

API / Usage

findAndReplaceDOMText has the following argument signature:

javascript
findAndReplaceDOMText(
  element, // (Element) The element or text-node to search within
  options  // (Object) Explained below
);

API

Options

The options object includes:

  • find (RegExp | String): Something to search for. A string will perform a global search by default (looking for all matches), but a RegExp will only do so if you include the global (/.../g) flag.
  • replace optional (String | Function): A String of text to replace matches with, or a Function which should return replacement Node or String. If you use a string, it can contain various tokens:
  • $n to represent the nth captured group of a regular expression (i.e. $1, $2, ...)
  • $0 or $& to represent the entire match
  • $` to represent everything to the left of the match.
  • $' to represent everything to the right of the match.
  • wrap optional (String | Node): A string representing the node-name of an element that will be wrapped around matches (e.g. span or em). Or a Node (i.e. a stencil node) that we will clone for each match portion.
  • wrapClass optional (String): A string representing the class name to be assigned to the wrapping element (e.g. found text). If the wrap option is not specified, then this option is ignored.
  • portionMode optional (String, one of "retain" or "first"): Indicates whether to re-use existing node boundaries when replacing a match with text (i.e. the default, "retain"), or whether to instead place the entire replacement in the first-found match portion's node. Most of the time you'll want the default.
  • filterElements optional (Function): A function to be called on every element encountered by findAndReplaceDOMText. If the function returns false the element will be altogether ignored.
  • forceContext optional (Function | Boolean): A boolean or a boolean-returning function that'll be called on every element to determine if it should be considered as its own matching context. See below under Contexts for more info.
  • preset optional (String): Currently there's only one preset: prose. See below.

preset:prose

The most common usage of findAndReplaceDOMText is to replace text found in regular prose, not all DOM nodes. To make this easier there is a preset that you can use to instruct it to:

  • Ignore non-textual elements (E.g. , , , , etc.)
  • Force bordered contexts on block-elements like and `

*JS*

```js
findAndReplaceDOMText(document.getElementById('container'), {
  find: 'function',
  replace: function(portion, match) {
    return '[[' + portion.index + ']]';
  }
});

Output HTML

xml

The wrap Option

If you pass a string to the wrap option, every matching text segment will be wrapped in that element. If you also specify the wrapClass option, the wrapping element will be assigned that class after it is created. This is useful for attaching various styles from your css.

E.g.

Input HTML

xml

JS

javascript
findAndReplaceDOMText(document.getElementById('container'), {
 find: 'without',
 wrap: 'em'
});
findAndReplaceDOMText(document.getElementById('container'), {
 find: 'with ',
 wrap: 'em',
 wrapClass: 'shiny'
});

CSS

css
.shiny {
 background-color: yellow;
}

Output HTML

xml

The instance

Calling findAndReplaceDOMText returns an instance of an internal Finder constructor -- the API on the object is limited, at the moment, to reverting:

javascript
var finder = findAndReplaceDOMText(...);

// Later:
finder.revert();

Note: Reversion will only work if the nodes have not been tampered with after the initial replacement -- if there have been removals, movements or normalisations then the reversion is not guarenteed to work. In this case it's best to retain your own clone of the target node(s) in order to run your own reversion.

Contexts

Matching, by default, will occur on all elements and across all element borders. E.g.

Before:

xml
javascript
findAndReplaceDOMText(document.getElementById('test'), {
  find: 'amazing',
  wrap: 'em'
});

After:

xml

This is a useful feature for inline elements, but is undesirable in many other cases, so to stop it from happening you can choose to "force a context" on those particular elements. In this case we want to force a context on elements:

javascript
findAndReplaceDOMText(document.getElementById('test'), {
  find: 'amazing',
  wrap: 'em',
  forceContext: function(el) {
    // Using https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
    return el.matches('p');
  }
});

Internally, the prose preset uses this feature:

javascript
exposed.PRESETS = {
  prose: {
    forceContext: exposed.NON_INLINE_PROSE,
    filterElements: function(el) {
      return !hasOwn.call(exposed.NON_PROSE_ELEMENTS, el.nodeName.toLowerCase());
    }
  }
};

…


This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to 

Issues· 26 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言