@igorskyflyer/mapped-replacer
v3.0.0
Published
🦗 Zero-dependency Map and RegExp based string replacer with Unicode support. 🍁
Maintainers
Readme
📃 Table of Contents
🤖 Features
- 🔄 Define or update single or multiple text replacement rules in one call
- 📚 Batch‑load rules from plain objects or key‑to‑array mappings
- 🔍 Toggle case‑sensitive or case‑insensitive matching via options
- 📏 Enable strict mode to match only whole words using compiled
RegExpboundaries - ✅ Check if a specific replacement rule exists before using it
- ❌ Remove individual rules without affecting others
- 📊 Get the exact number of active rules at any time
- 🧹 Clear all rules instantly to start fresh
- ✏️ Replace all matches in a string in a single, efficient pass
- 🌐 Match Unicode, emojis, and non‑Latin scripts with the u flag
- ⚡ Zero‑dependency, lightweight, TypeScript‑ready ES module
🕵🏼 Usage
Install it by executing any of the following, depending on your preferred package manager:
pnpm add @igorskyflyer/mapped-replaceryarn add @igorskyflyer/mapped-replacernpm i @igorskyflyer/mapped-replacer🤹🏼 API
❗ IMPORTANT
Why use
replaceWith→searchForinstead of the usualsearchFor→replaceWith?Instead of looping over each search term and rescanning the input
O(n × m), all rules are pre‑compiled into a single alternation regex once (O(totalKeyLength × log n)with sorting). At runtime, replacements happen in a singleO(m)pass with constant‑time map lookups, reducing repeated scans and ensuring longest‑match‑first priority without extra cost. In practice, this can cut runtime by up to ~90% when handling dozens or hundreds of patterns on large inputs, since the search cost collapses fromnfull scans to justone.
constructor
constructor(options?: IOptions): MappedReplacerCreates a new instance of MappedReplacer.
IOptions
options is a variable of type IOptions defined as:
caseSensitive- A Boolean that indicates whether replacing should be case-sensitive or not. Default istrue.strict- A Boolean that indicates whether strict mode is enabled. In strict mode, only whole matches are replaced. Default isfalse.longestMatchFirst- Whentrue, overlapping search patterns are matched in order of longest pattern length first, rather than the order they were added. This prevents shorter patterns from "stealing" matches that should belong to longer, more specific patterns.Usefalseonly if you need strict insertion-order precedence. Default istrue.
addRule()
addRule(replaceWith: string, searchFor: string): booleanAdds a new rule used in replacing a single string.
replaceWith - The string to replace the searchFor with.
searchFor - The string to be replaced.
Returns true if the rule was added successfully, false otherwise.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('😀', ':smile:')
console.log(mapper.replace('Hello world :smile:')) // outputs 'Hello world 😀'
addRule()
addRule(replaceWith: string, searchFor: string[]): booleanAdds a new rule for character replacement with multiple subjects.
replaceWith - The string to replace the searchFor with.
searchFor - The array of strings to be replaced.
Returns true if the rule was added successfully, false otherwise.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('😀', [':smile:', ':D'])
console.log(mapper.replace('Hello world :smile: :D')) // outputs 'Hello world 😀 😀'addRules()
addRules(rules: { [replaceWith: string]: string }): booleanAdds rules for string replacement.
rules - A simple key-value object, i.e.:
{
'<' : '<',
'>' : '>'
}Returns a Boolean whether the rules were added successfully.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRules({
'𝕋' : '𝕋',
'≈' : '≈',
'𝔱' : '𝔱'
})
console.log(mapper.replace('𝕋 ≈ 𝔱')) // outputs '𝕋 ≈ 𝔱'addRules()
addRules(rules: { [replaceWith: string]: string[] }): booleanAdds rules for string replacement.
rules - A simple key-value[] object, i.e.:
{
'😁' : [':D', ':-D'],
'😛' : [':P', ':-P']
}Returns a Boolean whether the rules were added successfully.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRules({
'😁' : [':D', ':-D'],
'😛' : [':P', ':-P']
})
console.log(mapper.replace('Hello :D world :-D this is a :P test :-P')) // outputs 'Hello 😁 world 😁 this is a 😛 test 😛'updateRule
updateRule(replaceWith: string, searchFor: string): booleanUpdates an existing rule used in replacing a single string.
replaceWith - The string to replace the searchFor with.
searchFor - The string to be replaced.
Returns true if the rule was updated, false otherwise.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('🤨', ':smile:')
mapper.updateRule('😀', ':smile:')
console.log(mapper.replace('Hello world :smile:')) // outputs 'Hello world 😀'
updateRule()
updateRule(replaceWith: string, searchFor: string[]): booleanUpdates an existing rule for character replacement with multiple subjects.
replaceWith - The string to replace the searchFor with.
searchFor - The array of strings to be replaced.
Returns true if the rule was updated, false otherwise.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('🤨', [':smile:', ':D'])
mapper.addRule('😀', [':smile:', ':D'])
console.log(mapper.replace('Hello world :smile: :D')) // outputs 'Hello world 😀 😀'hasRule()
hasRule(rule: string): booleanChecks whether a rule is present in the Map.
rule - The rule to check for.
Returns a Boolean indicating the existence of the given rule.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('𝕋', '𝕋')
mapper.addRule('≈', '≈')
console.log(mapper.hasRule('𝕋')) // trueremoveRule()
removeRule(searchFor: string): booleanRemoves the rule that matches the provided value.
searchFor - The rule to remove.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('𝕋', '𝕋')
mapper.addRule('≈', '≈')
mapper.removeRule('𝕋')
console.log(mapper.replace('𝕋 ≈ 𝔱')) // outputs '𝕋 ≈ 𝔱'rulesCount()
rulesCount(): numberGets the number of rules for string replacing.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('𝕋', '𝕋')
console.log(mapper.rulesCount()) // outputs 1clearRules()
clearRules(): voidClears all the rules.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('𝕋', '𝕋')
mapper.clearRules()
console.log(mapper.rulesCount()) // outputs 0replace(input: string)
replace(input: string): stringReplaces the values in the input with the values from the Map.
input - The input string.
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('→', '→')
console.log(mapper.replace('a → b')) // outputs 'a → b'🗒️ Examples
example.ts
import { MappedReplacer } from '@igorskyflyer/mapped-replacer'
const mapper: MappedReplacer = new MappedReplacer()
mapper.addRule('→', '→')
console.log(mapper.replace('a → b')) // outputs 'a → b'📝 Changelog
📑 The changelog is available here, CHANGELOG.md.
🪪 License
Licensed under the MIT license which is available here, MIT license.
💖 Support
🧬 Related
🧵 Provides ways of checking whether a String is present in an Array of Strings using custom Comparators. 🔍
✒ DúöScríbî allows you to convert letters with diacritics to regular letters. 🤓
@igorskyflyer/strip-yaml-front-matter
🦓 Strips YAML front matter from a String or a file. 👾
🏃♂️ Fast and simple Map and RegExp based HTML entities encoder. 🍁
🥞 Removes HTML code from the given string. Can even extract text-only from the given an HTML string. ✨
👨🏻💻 Author
Created by Igor Dimitrijević (@igorskyflyer).
