string-format-helpers
v0.2.0
Published
Lightweight string formatting, array sorting, datastructures helpers
Maintainers
Readme
string-format-helpers
Lightweight string formatting helpers: casing conversions, slugify, template formatting, truncate, padding, and more. Zero-dependency, ESM-only.
Features
- Casing: camelCase, PascalCase, snake_case, kebab-case, Title Case
- Slugify and humanize
- Safe trimming and ASCII normalization (remove diacritics)
- Templating: format("Hello {name}", { name: "Tomas" })
- Truncate (by characters or words) and pad (left/right/both)
- Strip HTML tags
- Sorting helpers: compare, stableSort, orderBy (multi-criteria)
- Pivoting helpers: groupBy, keyBy, transpose (2D array), pivotTable (rows x cols aggregation)
- Hash/object helpers: createHash, setIn/updateIn/deleteIn (immutable by default), merge (deep/shallow)
- Tree helpers: buildTree (from id/parentId), walkTree (traverse), findInTree, mapTree (immutable)
Installation
Using npm: npm install string-format-helpers
Using yarn: yarn add string-format-helpers
Using pnpm: pnpm add string-format-helpers
Usage
ESM import (Node.js >=14 or any bundler):
import sf, { camelCase, titleCase, format, slugify, pad, truncate } from 'string-format-helpers';
console.log(camelCase('Hello world')); // 'helloWorld' console.log(titleCase('hello world')); // 'Hello World' console.log(slugify('Crème brûlée!')); // 'creme-brulee' console.log(format('Hello, {name}!', { name: 'Tomas' })); // 'Hello, Tomas!' console.log(truncate('This is a long sentence', 12)); // 'This is a …' console.log(pad('42', 5, '0', 'left')); // '00042'
// Or use the default export console.log(sf.kebabCase('Hello World')); // 'hello-world'
API
All functions are pure and return strings unless noted.
toAscii(input) Normalize a string to ASCII by removing diacritics.
safeTrim(input) Trim safely; null/undefined become empty string.
capitalize(input) Uppercase the first character.
titleCase(input) Capitalize the first letter of each word.
camelCase(input) Convert to lower camelCase.
pascalCase(input) Convert to PascalCase.
snakeCase(input) Convert to snake_case.
kebabCase(input) Convert to kebab-case.
slugify(input) URL-friendly lowercase slug.
humanize(input) Convert technical strings to friendly words.
truncate(input, maxLength = 100, options) Truncate by characters (default) or words (options.byWords = true). Options: { omission = '…', byWords = false }.
pad(input, length, char = ' ', direction = 'right') Pad string to length. direction: 'left' | 'right' | 'both'.
stripTags(input) Remove HTML tags.
format(template, params) Simple templating with {placeholders}.
Hash/object helpers
createHash(entries | obj) Create a plain object from [key, value] entries or clone an existing object.
setIn(obj, path, value, options) Set a nested value by path (array or dot string). Immutable by default. Example: const obj = { a: { b: 1 } }; const next = setIn(obj, 'a.c', 2); // { a: { b: 1, c: 2 } }
updateIn(obj, path, updater, options) Update a nested value using an updater: (current) => next.
deleteIn(obj, path, options) Delete a nested key. Immutable by default.
merge(target, ...sources, options) Deep merge plain objects. Arrays: replace (default) or concat.
Tree helpers
buildTree(list, { id='id', parentId='parentId', children='children', rootParent=null }) Build a forest (array of roots) from a flat list with id/parentId.
walkTree(nodes, visitor, { childrenKey='children', order='pre'|'post' }) Traverse nodes and call visitor(node, context).
findInTree(nodes, predicate) Return first node matching predicate.
mapTree(nodes, mapper) Create a new tree by mapping each node (immutable).
TypeScript
The package is JS-only but is compatible with TypeScript via type inference on usage. If you need types, you can add a community .d.ts later.
Package structure
- src/index.js — ESM module with named and default exports
- package.json — ESM config, exports, publish settings
- README.md — documentation
- LICENSE — MIT
Development
Quick test to ensure the module loads: npm test
Try functions in Node REPL: node
import * as sf from './src/index.js'; sf.camelCase('hello world');
Publishing (npm)
Ensure you are logged in: npm login
Update version per semver: npm version patch # or minor / major
Publish the package: npm publish --access public
Notes:
- The package is ESM-only ("type": "module").
- The publishConfig is set for public publishing. For scoped packages (e.g., @your-scope/pkg), keep --access public.
License
MIT © Contributors
Troubleshooting: "Set the BROWSER environment variable to your desired browser" (npm error)
This message usually comes from tools that try to open your default browser (for example, react-scripts start in Create React App). This library itself does not open a browser, but if you see this error while working in the same environment, set the BROWSER environment variable explicitly.
Common values:
- chrome
- firefox
- edge
- none (disables auto-opening the browser)
Quick, temporary settings (one-off):
- macOS/Linux (Bash, Zsh):
- Open a specific browser:
BROWSER=chrome npm start - Disable opening a browser:
BROWSER=none npm start
- Open a specific browser:
- Windows PowerShell:
- Open a specific browser:
$env:BROWSER = "chrome"npm start
- Disable opening a browser:
$env:BROWSER = "none"npm start
- Open a specific browser:
- Windows cmd.exe:
- Open a specific browser:
set BROWSER=chrome && npm start - Disable opening a browser:
set BROWSER=none && npm start
- Open a specific browser:
Set permanently (so you don't have to set it every time):
- Windows PowerShell (current user):
[Environment]::SetEnvironmentVariable("BROWSER", "chrome", "User")
- Windows cmd.exe (current user):
setx BROWSER chrome
- macOS/Linux (Bash):
echo 'export BROWSER=chrome' >> ~/.bashrc && source ~/.bashrc
- macOS/Linux (Zsh):
echo 'export BROWSER=chrome' >> ~/.zshrc && source ~/.zshrc
Notes:
- Use
BROWSER=noneif you prefer no browser to be opened automatically. - If you're operating inside WSL and want to launch the Windows browser, ensure
wslviewis installed or setBROWSERto a Windows browser executable available on PATH (e.g.,"/mnt/c/Program Files/Google/Chrome/Application/chrome.exe").
