How Lodash camelCase Formats and Cleans Strings

The _.camelCase function in the Lodash JavaScript library converts strings into standard camel case by removing punctuation, spaces, and symbols while standardizing capitalization. Rather than manually deleting illegal characters one by one, Lodash breaks the input string into a list of distinct word tokens using regular expressions, strips out all non-word delimiters, and rebuilds the final string with a lowercase first word followed by capitalized subsequent words.

Word Segmentation via Internal Regular Expressions

Lodash handles character stripping at the parsing stage. Under the hood, _.camelCase is built using a higher-order utility called createCompounder. This helper immediately invokes Lodash's internal words function to split the source string into an array of recognizable word tokens.

The words method uses complex Unicode-aware regular expressions designed to capture:

Because this pattern only captures valid alphanumeric sequences, symbols such as dashes (-), underscores (_), spaces, periods, asterisks, and emojis are treated as delimiters. They are excluded from the matched tokens and completely discarded.

Assembly and Capitalization

Once the input string is parsed into an array of isolated words, createCompounder iterates through the tokens using an array reduction:

  1. The First Token: The first extracted word is converted entirely to lowercase using JavaScript's native string lowering methods.
  2. Subsequent Tokens: Every word after the first is transformed using Lodash's internal upperFirst logic. The first character of each word is converted to uppercase, while the remaining characters are normalized to lowercase.
  3. Concatenation: The formatted tokens are joined directly together without any separating characters, spaces, or hyphens.

Example Transformation Behavior

Consider the following input:

_.camelCase('--FOO-BAR__baz 123!');

The transformation steps occur as follows:

  1. Token Extraction: Lodash identifies the word segments, producing ['FOO', 'BAR', 'baz', '123']. The dashes, underscores, spaces, and the exclamation mark are omitted entirely.
  2. Casing Normalization:
    • 'FOO' becomes 'foo' (first word lowercased).
    • 'BAR' becomes 'Bar' (subsequent word capitalized).
    • 'baz' becomes 'Baz' (subsequent word capitalized).
    • '123' remains '123' (numbers retain their value).
  3. Joining: The segments are joined to yield the final output: 'fooBarBaz123'.

By combining regex-based token matching with programmatic case formatting, _.camelCase sanitizes inputs of any arbitrary format—including kebab-case, snake_case, or mixed punctuation—into clean, consistent camel-cased identifiers.