Skip to main content
Get up and running with trie-rules in just a few steps. This guide will walk you through installation, building your first trie, and performing search and replace operations.

Installation

1

Install the package

Install trie-rules using your preferred package manager:
npm install trie-rules
2

Import the library

Import the functions you need from trie-rules:
import { buildTrie, searchAndReplace, MatchType, CaseSensitivity } from 'trie-rules';
3

Create your first rule set

Define rules that specify what text to find and what to replace it with:
const rules = [
  {
    from: ['example', 'sample'],
    to: 'demo',
  },
  {
    from: ['specificword'],
    to: 'replacement',
    options: {
      match: MatchType.Whole,
    },
  },
  {
    from: ["al-Qur'an"],
    to: 'al-Qurʾān',
    options: {
      match: MatchType.Whole,
    },
  },
];
4

Build the trie

Construct a trie data structure from your rules:
const trie = buildTrie(rules, { normalizeApostrophes: true });
The normalizeApostrophes option treats all apostrophe-like characters (’, ’, `, ʾ, ʿ) as equivalent during matching.
5

Perform search and replace

Use the trie to transform your text:
const text = 'This is an example of text. We visited the Ka`bah yesterday.';
const result = searchAndReplace(trie, text);
console.log(result);
// Output: 'This is a demo of text. We visited the Kaʿbah yesterday.'

Complete example

Here’s a complete working example that demonstrates basic usage:
import { buildTrie, searchAndReplace, MatchType } from 'trie-rules';

// Define your rules
const rules = [
  {
    from: ['hello', 'hi'],
    to: 'greetings',
  },
  {
    from: ['world'],
    to: 'universe',
    options: {
      match: MatchType.Whole,
    },
  },
];

// Build the trie
const trie = buildTrie(rules);

// Transform text
const text = 'Hello world! Say hi to the world.';
const result = searchAndReplace(trie, text);

console.log(result);
// Output: 'greetings universe! Say greetings to the universe.'

Next steps

Now that you have trie-rules working, explore these key features:

API Reference

Explore the complete API documentation

Advanced Matching

Learn about match types, case sensitivity, and clipping

Rule Optimization

Automatically consolidate redundant patterns

Live Demo

Try the interactive demo in your browser
Check out the performance guide to see how trie-rules compares to regex-based solutions.

Build docs developers (and LLMs) love