The searchAndReplace function takes a trie data structure and a text string as inputs and searches the text for words that match any of the sources described in the trie. When a match is found, it replaces the word in the text with the corresponding target word from the trie.
A callback function that determines whether a rule should be considered based on confirmation options. Allows for dynamic decision-making during the replacement process.
type ConfirmCallback = (confirmOptions: ConfirmOptions) => boolean;
The modified text after replacements. A new string with all occurrences of the source words replaced by their corresponding target words as defined by the rules in the trie.
import { buildTrie, searchAndReplace } from 'trie-rules';// Define your rulesconst rules = [ { from: ["Ka'bah"], to: 'Kaʿbah', },];// Build the trie from the rules with apostrophe normalizationconst trie = buildTrie(rules, { normalizeApostrophes: true });// The text you want to processconst text = 'We visited the Ka`bah yesterday.';// Perform the search and replace operationconst replacedText = searchAndReplace(trie, text);console.log(replacedText);// Output: 'We visited the Kaʿbah yesterday.'
If the trie was built with normalizeApostrophes: true, the search operation will automatically treat all apostrophe-like characters (’, ’, `, ʾ, ʿ) as equivalent to the standard apostrophe (’) for matching purposes.
When multiple patterns can match at the same position, the function prioritizes longer matches over shorter ones by tracking the last valid match and continuing to search for potentially longer matches.
The function handles clipping adjustments for rules that specify clipStartPattern or clipEndPattern options, removing specified characters immediately before or after the match.