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

prevOpen Source→string-split-by-whitespacenext

string-split-by-whitespace4.2.1

Split string into array by chunks of whitespace

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • PURPOSE
  • API — SPLITBYW()
  • OPTS — IGNORERANGES
  • API — DEFAULTS
  • API — VERSION
  • API — TYPES
  • Changelog

Installation

Quick Take

Examples

  • Exclude a template variable range from the returned words
  • Split on line breaks, tabs, and repeated spaces

Purpose

When String.split(/\s+) is not enough, for example, when you need to exclude certain substrings, this program will help.

It splits the string by whitespace — definition of “whitespace” being “anything that trims to zero-length” — that’s tabs, line breaks (CR and LF), space character and raw non-breaking space. There are quite few Unicode characters across the whole Unicode range.

API — splitByW()

The main function splitByW() is imported like this:

It’s a function which takes three input arguments:

Input argumentTypeObligatoryDescription
str
Type: String
Obligatory: yes
strStringyesSource string.
opts
Type: Plain object
Obligatory: no
optsPlain objectnoOptional Options Object.

The Optional Options Object has the following shape:

KeyTypeDefaultDescription
ignoreRanges
Type: Array of zero or more range arrays
Default: []
ignoreRangesArray of zero or more range arrays[]Feed zero or more string slice ranges, arrays of two natural number indexes, like [[1, 5], [6, 10]]. Algorithm will not include these string index ranges in the results.

Here are all defaults in one place for copying:

The function will return an array of zero or more strings. Empty string yields empty array.

opts.ignoreRanges

Some basics first. “Heads” and “tails” here mean some templating literals that wrap a value. “heads” is frontal part, for example {{ below, “tails” is ending part, for example }} below:

Hi {{ firstName }}!

Now imagine you extracted heads and tails and you know their ranges: [[3, 5], [16, 18]]. (If you select {{ and }} from in front of “Hi” to where each head and tail starts and ends, you’ll see that these numbers match).

Now imagine you want to split Hi {{ firstName }}! into array ["Hi", "firstname", "!"].

For that you need to skip two ranges, those of a head and tail.

That’s where opts.ignoreRanges become handy.

In the example below, the library string-find-heads-tails is used to extract the ranges of variables’ heads and tails in a string, then split by whitespace:

const input = "some interesting {{text}} {% and %} {{ some more }} text.";
const headsAndTails = strFindHeadsTails(input, ["{{", "{%"], ["}}", "%}"]).reduce((acc, curr) => {
  acc.push([curr.headsStartAt, curr.headsEndAt]);
  acc.push([curr.tailsStartAt, curr.tailsEndAt]);
  return acc;
}, []);
const res1 = split(input, {
  ignoreRanges: headsAndTails,
});
console.log(`res1 = ${JSON.stringify(res1, null, 4)}`);
// => ['some', 'interesting', 'text', 'and', 'some', 'more', 'text.']

You can ignore whole variables, from heads to tails, including variable’s names:

const input = "some interesting {{text}} {% and %} {{ some more }} text.";
const wholeVariables = strFindHeadsTails(input, ["{{", "{%"], ["}}", "%}"]).reduce((acc, curr) => {
  acc.push([curr.headsStartAt, curr.tailsEndAt]);
  return acc;
}, []);
const res2 = split(input, {
  ignoreRanges: wholeVariables,
});
// => ['some', 'interesting', 'text.']

You need to perform the array.reduce to adapt to the string-find-heads-tails output, which is in format (index numbers are only examples):

[
  {
    headsStartAt: ...,
    headsEndAt: ...,
    tailsStartAt: ...,
    tailsEndAt: ...,
  },
  ...
]

and with the help of array.reduce you turn it into the format this program wants:

(first example with res1)

[
  [headsStartAt, headsEndAt],
  [tailsStartAt, tailsEndAt],
  ...
]

(second example with res2)

[
  [headsStartAt, tailsEndAt],
  ...
]

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:

API — types

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

TypeDescription
Opts
Type: Opts
OptsThe Optional Options Object of splitByW(), documented above.
Range
Type: Range
RangeA single range — the element type of opts.ignoreRanges.
import type { Opts, Range } from "string-split-by-whitespace";

Changelog

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