Skip to content
do- edited this page Jan 3, 2022 · 19 revisions

Description

string-escape-map is a class providing just one method: escape all "unsafe" characters in a given string, i. e., replace them with substrings from a predefined mapping.

Installation

npm install string-escape-map

Usage

const stringEscape = require ('string-escape-map')

// initialization
const MY_ESC = new stringEscape ([
  ['\t', '\\t'],
  ['\n', '\\n'],
  [ "'", "''"],
])

// possible later adjustment
MY_ESC.set ('\r', '')

// run time usage
const unsafeString = `Don't
you?`

const safeString = MY_ESC.escape (unsafeString)

Details

Constructor

The class provided by string-escape-map is derived from Map and shares its constructor argument format: if set, it must be an iterable of key-value pairs.

Additional restrictions on input are same as for the set method (see below).

Methods

set

The standard set method is overloaded to effectively store char codes to safe substring mapping. So:

  • key and value must be (primitive) strings;
  • key must be a single character string.

Under the hood, the key parameter is subject to charCodeAt.

escape

This method executes the module's main task: replaces all the characters in question with their safe representations

const safeString = MY_ESC.escape (unsafeString)

Parameter

unsafeString must be a primitive string.

null, undefined etc. values cause assertion errors.

Zero length strings are allowed.

Return value

A primitive string with all occurrences of each character previously set replaced with corresponding substrings.

Implementation notes

No replace nor replaceAll method is used.

No regular expression is constructed.

The given string is scanned with charCodeAt (which is significantly faster and more memory efficient than charAt).

If no unsafe character is ever found, the argument is passed through untouched, without creating any temporary object at all.

Otherwise, the resulting string is created by concatenating complete safe slices with replacement substrings for unsafe chars.

Clone this wiki locally