:mag: Find and replace DOM text
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:
123 456 Hello
findAndReplaceDOMText(document.getElementById('t'), {
find: /Hello/,
wrap: 'em'
});This would result in:
123 456 Hello
And it also works when matches are spread across multiple nodes! E.g.
123 456 Hello Goodbye
findAndReplaceDOMText(document.getElementById('t'), {
find: /Hello/,
wrap: 'em'
});This would result in:
123 456 Hello Goodbye
The EM element has been added twice, to cover both portions of the match.
Grab the latest findAndReplaceDOMText.js (or npm install findandreplacedomtext) and include it as a `` on your page.
findAndReplaceDOMText has the following argument signature:
findAndReplaceDOMText(
element, // (Element) The element or text-node to search within
options // (Object) Explained below
);The options object includes:
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.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 right of the match.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.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.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.Function): A function to be called on every element encountered by findAndReplaceDOMText. If the function returns false the element will be altogether ignored.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.String): Currently there's only one preset: prose. See below.preset:proseThe 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:
, , , , etc.) and `
*JS*
```js
findAndReplaceDOMText(document.getElementById('container'), {
find: 'function',
replace: function(portion, match) {
return '[[' + portion.index + ']]';
}
});Output HTML
wrap OptionIf 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
JS
findAndReplaceDOMText(document.getElementById('container'), {
find: 'without',
wrap: 'em'
});
findAndReplaceDOMText(document.getElementById('container'), {
find: 'with ',
wrap: 'em',
wrapClass: 'shiny'
});CSS
.shiny {
background-color: yellow;
}Output HTML
Calling findAndReplaceDOMText returns an instance of an internal Finder constructor -- the API on the object is limited, at the moment, to reverting:
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.
Matching, by default, will occur on all elements and across all element borders. E.g.
Before:
findAndReplaceDOMText(document.getElementById('test'), {
find: 'amazing',
wrap: 'em'
});After:
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:
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:
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 No open issues yet, or sync has not completed.