No dependencies whatsoever. This package declares no dependencies or devDependencies.
Permalink to InstallationInstallation
Permalink to Quick TakeQuick Take
Permalink to ExamplesExamples
- Collapse boundary whitespace containing line breaks
- Preserve CRLF line endings
- Keep a chosen number of leading and trailing line breaks
- Preserve non-breaking-space boundaries
- Pass through non-string input
- Leave whitespace inside a multiline string unchanged
- Preserve a string that has no boundary whitespace
- Collapse strings containing only whitespace
Purpose
collWhitespace() normalises whitespace at the beginning and end of a string. Use it before concatenating string fragments so their boundaries do not introduce unwanted spaces or line breaks.
For example, ranges-push uses this package when it merges replacement strings.
The function preserves whitespace between the first and last non-whitespace characters. To normalise whitespace throughout a string, use string-collapse-white-space.
API — collWhitespace()
The main function collWhitespace() is imported like this:
The function accepts a required value and an optional line-break limit:
| Input argument | Type | Required | Default | Description |
|---|---|---|---|---|
strType: Any value Default: None | ||||
str | Any value | Yes | None | String to process, or a non-string value to return unchanged |
lineBreakLimitType: Non-negative integer number Default: 1 | ||||
lineBreakLimit | Non-negative integer number | No | 1 | Maximum logical CR, LF, or CRLF line breaks to retain at each boundary of a string |
For string input, lineBreakLimit controls each boundary independently. A value of 0 removes all boundary line breaks. A positive integer retains no more than that many logical line breaks, with CRLF counted as one.
At runtime, every invalid limit—including a fraction, negative number, NaN, infinity, string, Boolean, nullish value, symbol, bigint, or object—falls back to 1. The function does not coerce the value or call object conversion hooks. TypeScript callers can supply only a number.
For non-string input, the function returns the original value unchanged. Its conditional generic type preserves the input type, and reference values retain their identity:
import { collWhitespace } from "string-collapse-leading-whitespace";
const value = { untouched: true };
console.log(collWhitespace(value) === value);
// => true
For string input, the function returns a string:
console.log(collWhitespace("\n\ncontent\n\n", 0));
// => "content"
console.log(collWhitespace("\n\n\ncontent\n\n\n", 2));
// => "\n\ncontent\n\n"
API — version
You can import version: