Collapse the leading and trailing whitespace of a string

Quick Take

import { strict as assert } from "assert";
import { collWhitespace } from "string-collapse-leading-whitespace";

// if leading/trailing whitespace doesn't contain \n, collapse to a single space
assert.equal(collWhitespace("  aaa   "), " aaa ");

// otherwise, collapse to a single \n (default setting)
  collWhitespace("     \n\n   aaa  \n\n\n    "),

// does nothing to trimmed strings:
assert.equal(collWhitespace("aaa"), "aaa");

// if there are multiple lines string is still processed in trim-fashion -
// only beginning and ending whitespace is changed:
  collWhitespace("  abc  \n  def  \n  ghi  "),
  " abc  \n  def  \n  ghi "


This program is aimed to process strings before concatenating them. It collapses the leading and trailing whitespace, if any, so that later the result looks reasonable.

For example, ranges-push uses it to merge to-be-inserted chunks of string.


collWhitespace(str, [lineBreakLimit])

In other words, it's a function which takes two input arguments, second one being optional (marked by square brackets).

API - Input

Input argument Type Obligatory? Default Description
str String yes undefined Source string to work on
lineBreakLimit Natural number or zero no 1 If whitespace contains linebreaks, it will be replaced by those linebreaks, count limited to this value

If first input argument is not a string, it will be just returned back, untouched. If second input argument is zero or falsy or not a number, it will be set to 1 and application will continue as normal.

API - Output

String of zero or more characters. If input was not a string, same input will be returned back, without an error.


See it in the monorepo opens in a new tab, on GitHub.


To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.


MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 detergent 8.0.1
Extracts, cleans and encodes text
📦 string-overlap-one-on-another 3.0.1
Lay one string on top of another, with an optional offset
📦 string-uglify 2.0.1
Shorten sets of strings deterministically, to be git-friendly
📦 string-trim-spaces-only 4.0.1
Like String.trim() but you can choose granularly what to trim
📦 string-unfancy 5.0.1
Replace all n/m dashes, curly quotes with their simpler equivalents
📦 string-remove-duplicate-heads-tails 6.0.1
Detect and (recursively) remove head and tail wrappings around the input string
📦 string-remove-thousand-separators 6.0.1
Detects and removes thousand separators (dot/comma/quote/space) from string-type digits