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 "

§ Purpose

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 argumentTypeObligatory?DefaultDescription
strStringyesundefinedSource string to work on
lineBreakLimitNatural number or zerono1If 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.

§ Changelog

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

§ Contributing

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.

§ Licence

MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 detergent 7.0.14
Extracts, cleans and encodes text
📦 string-unfancy 4.0.14
Replace all n/m dashes, curly quotes with their simpler equivalents
📦 string-left-right 4.0.14
Looks up the first non-whitespace character to the left/right of a given index
📦 string-fix-broken-named-entities 5.2.4
Finds and fixes common and not so common broken named HTML entities, returns ranges array of fixes
📦 string-trim-spaces-only 3.0.14
Like String.trim() but you can choose granularly what to trim
📦 string-extract-sass-vars 2.0.14
Parse SASS variables file into a plain object of CSS key-value pairs
📦 string-strip-html 8.2.11
Strips HTML tags from strings. No parser, accepts mixed sources