printable-characters
A little helper for handling strings containing zero width characters, ANSI styling, whitespaces, newlines, weird Unicode 💩 symbols, etc.
Determining the real (visible) length of a string
const strlen = // === 7 // === 7
Detecting blank text
const isBlank = // === false // === true
Obtaining a blank string of the same width
const blank = // === ' ' // === ' ' // === '\t \n ') // === ' \t'
Matching invisible characters
const ansiEscapeCodes zeroWidthCharacters = const s = '\u001b[106m' + 'foo' + '\n' + 'bar' + '\u001b[49m' s // === 'foo\nbar' // === 'foobar'
Getting the first N visible symbols, preserving the invisible parts
Use for safely truncating strings to maximum width without breaking ANSI codes:
const first = const s = '\u001b[22mfoobar\u001b[22m' // === '\u001b[22m\u001b[22m' // === '\u001b[22mf\u001b[22m' // === '\u001b[22mfoo\u001b[22m' // === '\u001b[22mfoobar\u001b[22m'
Extracting the invisible parts followed by the visible ones (parsing)
const partition = // [ ]) // [['', 'foo'] ]) // [['\u001b[1m', 'foo'] ]) // [['\u001b[1m', 'foo'], ['\u0000', 'bar'] ]) // [['\u001b[1m', 'foo'], ['\u0000', 'bar'], ['\n', '']])
Applications
- as-table — a simple function that prints objects as ASCII tables
- string.bullet — ASCII-mode bulleting for the list-style data
- string.ify — a fancy pretty printer for the JavaScript entities
- Ololog! — a better
console.log
for the log-driven debugging junkies!
TODO
Handle multi-component emojis, as in this article:
assert // FAILING, see http://blog.jonnew.com/posts/poo-dot-length-equals-two for possible solutionassert // FAILING, see http://blog.jonnew.com/posts/poo-dot-length-equals-two for possible solution