mapped-replacer

πŸ—Ί Zero-dependency Map and RegExp based string replacer with Unicode support. 🍁

Usage no npm install needed!

<script type="module">
  import mappedReplacer from 'https://cdn.skypack.dev/mapped-replacer';
</script>

README

πŸ—Ί Mapped Replacer 🍁


Zero-dependency Map and RegExp based string replacer with Unicode support.


Requires ES6 or later, for compatibility check this Can I Use link.


✨Since v.1.1.0 Mapped Replacer is a hybrid module that supports both CommonJS (legacy) and ES modules, thanks to Modern Module.


Table of contents


Install

npm i mapped-replacer

API

addRule(key: string, value: string): boolean

Adds a new rule or updates the existing rule for character replacing.

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRule(':smile:', 'πŸ˜€')

console.log(mapper.replace('Hello world :smile:')) // outputs 'Hello world πŸ˜€'

addRules(rules: Object): boolean

Adds rules or updates the existing rules for character replacing.
Passed object is a simple key-value object, i.e. { '<': '&#60;', '>': '&#62;'}

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRules({
  '𝕋': '&#120139;',
  'β‰ˆ': '&#8776;',
  '𝔱': '&#120113;',
})

console.log(mapper.replace('𝕋 β‰ˆ 𝔱')) // outputs '&#120139; &#8776; &#120113;'

removeRule(key: string): boolean

Removes the rule that matches the provided key.

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRule('𝕋', '&#120139;')
mapper.addRule('β‰ˆ', '&#8776;')

mapper.removeRule('𝕋')

console.log(mapper.replace('𝕋 β‰ˆ 𝔱')) // outputs '𝕋 &#8776; 𝔱'

rulesCount(): number

Gets the number of rules for character replacing.

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRule('𝕋', '&#120139;')

console.log(mapper.rulesCount()) // outputs 1

clearRules(): void

Clears all the rules.

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRule('𝕋', '&#120139;')
mapper.clearRules()

console.log(mapper.rulesCount()) // outputs 0

replace(input: string): string

Replaces the values in the input that match the keys in the Map object.

import { MappedReplacer } from 'mapped-replacer'

const mapper = new MappedReplacer()

mapper.addRule('β†’', '&#8594;')

console.log(mapper.replace('a β†’ b')) // outputs 'a &#8594; b'

Test

npm test