collapse-white-space
A tiny ESM utility that collapses runs of whitespace into a single character.
Repository Health
Technical Analysis
collapse-white-space is a small, focused JavaScript utility that collapses multiple consecutive whitespace characters in a string down to one. It supports both JavaScript whitespace (matching \s) and stricter HTML whitespace, so you can normalize text the way a browser or a parser would.
Beyond simple collapsing, it can optionally preserve line endings — collapsing a run of whitespace that contains a newline down to that newline rather than a space — and trim leading and trailing whitespace. It is ESM-only, fully typed with TypeScript, and has no dependencies, making it a common building block in text- and markdown-processing pipelines.
What You Get
- A collapseWhiteSpace() function that reduces whitespace runs to a single character
- Selectable ‘js’ or ‘html’ whitespace matching semantics
- A preserveLineEndings option that keeps newlines instead of collapsing to a space
- A trim option to drop leading and trailing whitespace
- Exported TypeScript Options and Style types with zero runtime dependencies
Common Use Cases
- Normalizing whitespace in text extracted from HTML or markdown
- Cleaning up user-entered strings before storage or comparison
- Building blocks within remark/rehype and other unified text pipelines
- Preparing strings for display where multiple spaces should render as one
Under The Hood
Architecture - The entire library is a single ~89-line index.js exporting one function. It resolves options (accepting a bare style string as shorthand), picks the appropriate whitespace regular expression for the chosen style, and walks the string collapsing matched runs — either to a single space or, when preserveLineEndings is set, to the line ending found within the run, with an optional trim pass on the boundaries.
Tech Stack - Pure ESM JavaScript with no runtime dependencies, typed via JSDoc plus a tsconfig for declaration generation. It targets Node.js 14.14+/16.0+, Deno, and modern browsers.
Code Quality - The implementation is minimal and battle-tested, shipping a test.js suite with full coverage reported through Codecov and documented as safe. The single-responsibility design keeps the surface tiny and easy to audit.
API Design - The API is one intuitively named function with sensible defaults, and the options object accepts a shorthand string for the common style-only case. Full TypeScript types and a thorough README make correct usage obvious with essentially no learning curve.