Like String.trim() but you can choose granularly what to trim

§ Quick Take

import { strict as assert } from "assert";
import trimSpaces from "string-trim-spaces-only";

assert.deepEqual(trimSpaces("  aaa   "), {
  res: "aaa",
  ranges: [
    [0, 2],
    [5, 8],

assert.deepEqual(trimSpaces("   \t  zz   \n    "), {
  res: "\t  zz   \n",
  ranges: [
    [0, 3],
    [12, 16],


trimSpaces(str, [opts])

In other words, it's a function which takes two input arguments, second-one being optional (marked by square brackets).

§ API - Function's Input

Input argumentKey value's typeObligatory?Description
inputStringyesInput string you want to trim some way
optsPlain objectnoAn Optional Options Object. See below for its API.

If input arguments are supplied have any other types, an error will be thrown.

§ Optional Options Object

An Optional Options Object's keyType of its valueDefaultDescription
classicTrimBooleanfalseIf set to true, trimming becomes the same as String.trim().
crBooleanfalseShould we trim the carriage returns (CR)
lfBooleanfalseShould we trim the line breaks (LF)
tabBooleanfalseShould we trim tabs
spaceBooleantrueShould we trim spaces
nbspBooleanfalseShould we trim raw non-breaking spaces

Here is the default options object in one place:

classicTrim: false,
cr: false,
lf: false,
tab: false,
space: true,
nbsp: false

§ API - Function's Output

Since v.2, the output is a plain object:

Key nameKey value's typeDescription
resString or zero or more charactersResult string after trimming.
rangesArray of zero or more arraysIf we trimmed anything, each slice range will be added into this array.

§ opts.classicTrim

String.trim() returns string but sometimes you need just ranges of what would be trimmed, to merge them into compiled ranges array and to process later, along everything else. In those cases, use opts.classicTrim. If you need just string value, it's not worth to use this function as a substitute for String.trim() for performance reasons.

§ 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:

📦 ranges-apply 4.0.2
Take an array of string index ranges, delete/replace the string according to them
📦 ranges-push 4.0.2
Gather string index ranges
📦 string-collapse-leading-whitespace 4.0.0
Collapse the leading and trailing whitespace of a string
📦 string-strip-html 7.0.3
Strips HTML tags from strings. No parser, accepts mixed sources
📦 string-extract-class-names 5.10.1
Extract class (or id) name from a string
📦 string-remove-thousand-separators 4.0.3
Detects and removes thousand separators (dot/comma/quote/space) from string-type digits
📦 string-find-heads-tails 3.17.0
Finds where are arbitrary templating marker heads and tails located