Aller au contenu principal

words()

words(str, pattern?): string[]

Splits string into an array of its words.

remarque

Default pattern handles camelCase, PascalCase, snake_case, kebab-case, and mixed strings.


Parameters

str: string

The string to inspect.

pattern?: string | RegExp

The pattern to match words (optional).


Returns: string[]

The array of words.


Since

2.0.0


Note

Includes Unicode letters and numbers in default pattern.


Performance

O(n) where n is string length. Single regex pass.


Also known as

words (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']

words('fred, barney, & pebbles', /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']

words('camelCase');
// => ['camel', 'Case']

words('PascalCase');
// => ['Pascal', 'Case']

words('snake_case');
// => ['snake', 'case']

words('kebab-case');
// => ['kebab', 'case']

words('XMLHttpRequest');
// => ['XML', 'Http', 'Request']

How it works?

Splits string into an array of its words. Handles camelCase, PascalCase, snake_case, kebab-case.

Case Detection

Custom Pattern


Use Cases

Parse variable names for display 📌

Convert code-style identifiers to readable words. Essential for auto-generating labels from API field names.

words('firstName');      // => ['first', 'Name']
words('XMLHttpRequest'); // => ['XML', 'Http', 'Request']

Build search indexes from content 📌

Extract searchable tokens from mixed-format content. Useful for building client-side search.

words('async-data in JavaScript_apps');
// => ['async', 'data', 'in', 'Java', 'Script', 'apps']

Slug generation from titles

Create URL-friendly slugs from titles with any naming convention.

words('How to Use XMLHttpRequest').join('-').toLowerCase();
// => 'how-to-use-xml-http-request'