string-collapse-leading-whitespace5.1.0

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

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.1.0
Extracts, cleans and encodes text
📦 string-extract-sass-vars 2.1.0
Parse SASS variables file into a plain object of CSS key-value pairs
📦 string-unfancy 4.1.0
Replace all n/m dashes, curly quotes with their simpler equivalents
📦 string-convert-indexes 4.1.0
Convert between native JS string character indexes and grapheme-count-based indexes
📦 string-overlap-one-on-another 2.1.0
Lay one string on top of another, with an optional offset
📦 string-strip-html 8.3.0
Strips HTML tags from strings. No parser, accepts mixed sources
📦 string-find-heads-tails 4.1.0
Finds where are arbitrary templating marker heads and tails located