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 Sourcehut.

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 detergent 6.1.1
Extracts, cleans and encodes text
📦 string-trim-spaces-only 2.9.0
Like String.trim() but you can choose granularly what to trim
📦 string-overlap-one-on-another 1.6.0
Lay one string on top of another, with an optional offset
📦 string-find-heads-tails 3.17.0
Finds where are arbitrary templating marker heads and tails located
📦 string-extract-sass-vars 1.3.0
Parse SASS variables file into a plain object of CSS key-value pairs
📦 string-unfancy 3.10.1
Replace all n/m dashes, curly quotes with their simpler equivalents
📦 string-split-by-whitespace 1.7.0
Split string into array by chunks of whitespace