@debkit/string
v1.2.0
Published
String formatting, serialization, slug, and template utilities
Maintainers
Readme
@debkit/string
String formatting, serialization, slug, and template utilities. Zero dependencies.
Install
npm install @debkit/stringAPI
Formatting
formatString(format, data, joinBy?)
Maps format keys to values from a data object and joins.
import { formatString } from '@debkit/string';
formatString(['first', 'last'], { first: 'John', last: 'Doe' }, ' ');
// 'John Doe'bindStringFormat(format, data, replacePairs?)
Replaces {key} placeholders in a template string.
import { bindStringFormat } from '@debkit/string';
bindStringFormat('Hello {name}, age {age}', { name: 'John', age: 30 });
// 'Hello John, age 30'splitString(str, splitBy?)
Splits a string by a delimiter.
boundString(str, boundChars?)
Pads a string with boundary characters.
import { boundString } from '@debkit/string';
boundString('hello', ['[', ']']); // '[hello]'padNumberString(num, length?)
Pads a number with leading zeros.
import { padNumberString } from '@debkit/string';
padNumberString(5, 3); // '005'
padNumberString('42', 5); // '00042'removeEndlines(str)
Strips \r\n and \n from a string.
slug(value?)
Converts a string to a URL-friendly slug.
import { slug } from '@debkit/string';
slug('Hello World!'); // 'hello-world'
slug(' Foo & Bar '); // 'foo-bar'resetTextStyle(str)
Strips ANSI escape codes from a string.
Serialization
serialize(data, space?)
JSON serialization with support for Map, Set, Date, and RegExp.
import { serialize, deserialize } from '@debkit/string';
const data = { users: new Map([['a', 1]]), created: new Date() };
const json = serialize(data);
const restored = deserialize(json); // Map and Date are restoreddeserialize(data)
Restores objects serialized with serialize(), including Map, Set, Date, and RegExp.
Utilities
valueOrDefault<T>(value, def)
Returns value if not null/undefined, otherwise def.
import { valueOrDefault } from '@debkit/string';
valueOrDefault(null, 'fallback'); // 'fallback'
valueOrDefault('value', 'fallback'); // 'value'randString<T>(models)
Picks a random element from a string array.
import { randString } from '@debkit/string';
randString(['a', 'b', 'c']); // random pickLicense
MIT
