string-collapse-leading-whitespace3.0.2

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)
assert.equal(
  collWhitespace("     \n\n   aaa  \n\n\n    "),
  "\naaa\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:
assert.equal(
  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.

§ API

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.

§ Licence

MIT opens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 detergent 5.11.7
Extracts, cleans and encodes text
📦 string-find-malformed 1.1.16
Search for a malformed string. Think of Levenshtein distance but in search.
📦 string-convert-indexes 2.0.2
Convert between native JS string character indexes and grapheme-count-based indexes
📦 string-apostrophes 1.2.30
Comprehensive, HTML-entities-aware tool to typographically-correct the apostrophes and single/double quotes
📦 string-trim-spaces-only 2.8.23
Like String.trim() but you can choose granularly what to trim
📦 string-remove-widows 1.6.17
Helps to prevent widow words in a text
📦 string-character-is-astral-surrogate 1.10.64
Tells, is given character a part of astral character, specifically, a high and low surrogate