Transliterate
This is a rewrite of the perl tr method.
To use
const tr = require('perl-transliterate');
tr(str, searchStr, replaceStr [, flags])
Without flags:
const tr = require('perl-transliterate');
let str = 'abba';
str = tr(str, 'ab', 'po');
console.log(str === 'poop');
Here we're taking a string we want to search through (abba
) and searching for instances of ab
to be replaced with po
: all instances of a
will be replaced with p
and all instances of b
will be replaced by o
.
With Flags:
s
const tr = require('perl-transliterate');
let str = 'abba';
str = tr(str, 'ab', 'po', 's');
console.log(str === 'pop');
The s
flag will squash characters that appear sequentially in a row, so becase b
is being replaced with o
and the s
flag is set, it will remove an instance of b
and replace with a single instance of o
creating: pop
. Whilst a
appears twice, they are not sequntial, and thus will each will be replaced with p
.
d
const tr = require('perl-transliterate');
let str = 'adam';
str = tr(str, 'adm', 'ev', 'd');
console.log(str === 'eve');
The d
flag will remove characters that appear in the search string but do not have a replacement string value. In the above example, m
is in the search string, but does not have a replacement string value, meaning that any m
found in the string will be removed.
ds
const tr = require('perl-transliterate');
let str = 'abba';
str = tr(str, 'ab', 'p', 'ds');
console.log(str === 'p');
d
and s
can be combined.