Skip to content

words

Splits a string into an array of words. null and undefined return [].

Handles camelCase, PascalCase, SCREAMING_SNAKE_CASE, kebab-case, snake_case, and regular whitespace-separated text. Numbers are treated as word tokens.

Available since v2.0.0

import { words } from '@helpers4/string';
words(str: string | null | undefined): string[]
ParameterTypeDescription
strstring | null | undefinedThe string to split into words.

string[] — An array of word tokens.

Splits camelCase, PascalCase, snake_case, kebab-case and space-separated words.

words('camelCaseString') // => ['camel', 'Case', 'String']
words('snake_case')       // => ['snake', 'case']
words('kebab-case')       // => ['kebab', 'case']
words('hello world')      // => ['hello', 'world']

Combine with a map to convert from any naming convention.

const toCamel = (str: string) =>
  words(str)
    .map((w, i) => i === 0 ? w.toLowerCase() : w[0].toUpperCase() + w.slice(1).toLowerCase())
    .join('');
toCamel('hello-world'); // => 'helloWorld'

View source on GitHub