Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→string-collapse-white-spacenext

string-collapse-white-space11.2.6

Replace chunks of whitespace with a single spaces

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • API — COLLAPSE()
  • API — DEFAULTS
  • API — VERSION
  • OPTS — CB
  • API — CBSCHEMA
  • API — TYPES
  • Changelog

No 3rd party dependencies. All dependencies and devDependencies, checked recursively, are Codsen packages.

Permalink to InstallationInstallation

Permalink to Quick TakeQuick Take

Permalink to ExamplesExamples

  • Minify a chunk of CSS selector
  • Collapse a run containing tabs
  • Replace tabs inside whitespace runs with ordinary spaces
  • Keep at most one consecutive empty line
  • Collapse but preserve one leading space
  • Preserve one space around each line's content
  • Collapse but preserve one trailing space
  • Remove empty lines from multiline text
  • Inspect the ranges used to produce the collapsed result
  • Trim whitespace from the start and end of every line
  • Trim multiline content whose boundaries contain non-breaking spaces
  • Trim raw non-breaking spaces with ordinary whitespace

API — collapse()

The main function collapse() is imported like this:

Collapse consecutive ASCII spaces and optionally trim or normalize other whitespace. Line breaks remain unless the trimming or empty-line options remove them.

Input argumentTypeObligatoryDescription
str
Type: String
Obligatory: yes
strStringyesSource string to work upon
opts
Type: Object
Obligatory: no
optsObjectnoOptions to override the defaults below.

The Optional Options Object has the following shape:

KeyTypeDefaultDescription
trimStart
Type: Boolean
Default: true
trimStartBooleantrueRemove leading whitespace, stopping at a protected non-breaking space.
trimEnd
Type: Boolean
Default: true
trimEndBooleantrueRemove trailing whitespace, stopping at a protected non-breaking space.
trimLines
Type: Boolean
Default: false
trimLinesBooleanfalseTrim each line without removing its CR, LF, or CRLF line break. Protected non-breaking spaces stop trimming within that line.
trimnbsp
Type: Boolean
Default: false
trimnbspBooleanfalseAllow trimming to remove non-breaking spaces (U+00A0) too.
removeEmptyLines
Type: Boolean
Default: false
removeEmptyLinesBooleanfalseRemove blank lines between content, retaining one line break plus the number of blank lines set below. A line containing only whitespace, including non-breaking spaces, is blank.
limitConsecutiveEmptyLinesTo
Type: Non-negative integer
Default: 0
limitConsecutiveEmptyLinesToNon-negative integer0Number of blank lines to retain when removeEmptyLines is true.
enforceSpacesOnly
Type: Boolean
Default: false
enforceSpacesOnlyBooleanfalseReplace each run of whitespace other than CR/LF with one ASCII space. This includes non-breaking spaces even when trimnbsp is false.
cb
Type: Function
Default: ({ suggested }) => suggested
cbFunction({ suggested }) => suggestedAccept, replace, or ignore each proposed range. Unchanged whitespace receives a null suggestion.

Trimming and empty-line removal take precedence over enforceSpacesOnly: a whitespace segment that is removed does not leave a replacement space. With trimnbsp: false, trimming still removes ordinary whitespace outside a protected non-breaking space. A non-breaking space on one line does not prevent trimming another line.

trimStart: false and trimEnd: false disable whole-string trimming. trimLines: true still trims the first and last lines. By default, ordinary space runs collapse, while other whitespace is preserved unless an enabled option changes it.

removeEmptyLines treats non-breaking-space-only lines as blank even when trimnbsp is false. Keep removeEmptyLines: false when those lines must remain.

collapse() uses the same options and callback contract in ESM and the direct-browser script.

\u00a0 below represents a non-breaking space:

collapse(" \u00a0a").result;
// => "\u00a0a"

collapse("a\t\nb", {
  trimLines: true,
  enforceSpacesOnly: true,
}).result;
// => "a\nb"

Here are all defaults in one place for copying:

Function will return a plain object (Res type above):

It has the following keys:

Key’s nameTypeDescription
result
Type: String
resultStringThe string output where all ranges were applied to it.
ranges
Type: ranges: an array of one or more arrays containing from-to string index ranges OR null
rangesranges: an array of one or more arrays containing from-to string index ranges OR nullFor example, if characters from index 0 to 5 and 30 to 35 were deleted, that would be [[0, 5], [30, 35]]. Another example, if nothing was found, it would put here null.

API — defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

API — version

You can import version:

opts.cb

The callback receives each proposed edit before it is applied. Return suggested to accept it, another range to customize it, or null to preserve that part of the input. The default callback is ({ suggested }) => suggested.

See examples.

When a whitespace run needs no edit, the callback receives suggested: null. It can still return a range to delete or replace that whitespace. Handle this nullable value before indexing suggested. A run that already produced an edit suggestion does not receive an additional null notification, even when the callback rejects that edit.

A run spanning several lines can produce multiple subrange suggestions. Each reports the boundaries of the complete whitespace run, while suggested identifies the particular edit. All indices refer to the original input, and end indices are exclusive. At the end of the input, whiteSpaceEndsAt equals str.length, including any trailing line breaks, tabs, and non-breaking spaces.

The callback receives one plain object:

KeyTypeDescription
suggested
Type: Range or null
suggestedRange or nullThe range this program would apply if you left it alone.
whiteSpaceStartsAt
Type: Natural number or null
whiteSpaceStartsAtNatural number or nullStart index of the complete whitespace run in the original input.
whiteSpaceEndsAt
Type: Natural number or null
whiteSpaceEndsAtNatural number or nullExclusive end index of the complete whitespace run in the original input.
str
Type: String
strStringThe input string, so the callback doesn’t have to close over it.

API — cbSchema

The list of opts.cb callback object’s key names, as an array of strings:

import { cbSchema } from "string-collapse-white-space";

console.log(cbSchema);
// => ["suggested", "whiteSpaceStartsAt", "whiteSpaceEndsAt", "str"]

It’s exported so that programs wrapping this one — and the unit tests — can assert that a callback object carries exactly these keys, without hardcoding the list in two places.

API — types

This package is written in TypeScript and exports the following types:

TypeDescription
Opts
Type: Opts
OptsThe Optional Options Object of collapse(), documented above.
Res
Type: Res
ResWhat collapse() returns — result and ranges.
Callback
Type: Callback
CallbackThe signature of opts.cb.
CbObj
Type: CbObj
CbObjThe plain object opts.cb is called with, shown above.
Extras
Type: Extras
ExtrasThe three positional keys of CbObj — whiteSpaceStartsAt, whiteSpaceEndsAt and str — without suggested.
Range
Type: Range
RangeA single range: a two- or three-element array.
RangesType
Type: RangesType
RangesTypeZero or more Ranges, or null. It’s named RangesType rather than Ranges to avoid a clash with the ranges-push class of that name.
import type { Callback, CbObj, Extras, Opts, Range, RangesType, Res } from "string-collapse-white-space";

Permalink to changelogChangelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab