Skip to content
do- edited this page Mar 23, 2024 · 27 revisions

string-replace-balanced is a CommonJS module exporting one class that encapsulates

  • a pair of start / end tokens,
  • a transform function

and contains a method to replace each ${start}${_}${end} fragment in a given string with the this.transform(_) value.

Installation

npm install string-replace-balanced

Usage

const TokenReplacer = require ('string-replace-balanced')

const 
  template = '<*~one*> and <*~two*> makes 3.',
  val = {one: 1, two: 2},

// (1) bag of options

const rpl = new TokenReplacer ({
  start     : '<*~',
  end       :  '*>',
  transform : name => val [name]
})

// (2) subclass

const rpl = new (class extends TokenReplacer {
  get start  () {return '<*~'}
  get end    () {return '*>'}
  transform (_) {return val [_]}
})

console.log (rpl.process (template))

// result: '1 and 2 makes 3.'

Notes

The same functionality is available via the standard String.prototype.replaceAll() method, but only with regular expressions which cause a certain performance overhead, avoidable by using string-replace-balanced instead.

The original purpose of this module is to scan HTML for pictures given as Data URLs ("data:image ... ") and to store them separately overriding the corresponding links.

Limitations

No character escaping is supported: start and end are always considered tag delimiters and cannot be isolated with /*...*/, <![CDATA[...]]> nor whatever alike.

Nested tags are not allowed: each start is expected to be closed with the nearest end.

The balance is not enforced though. For example, multiple end tokens may occur in a row — they will be copied into the result as is without reporting an error.

Clone this wiki locally