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:
- Sequences of alphanumeric characters.
- Transitions between lowercase and uppercase letters (handling camelCase or PascalCase inputs).
- Sequences of uppercase letters followed by a lowercase letter
(handling acronyms like
HTMLParserintoHTMLandParser). - Numerical sequences grouped with adjacent words or as standalone segments.
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:
- The First Token: The first extracted word is converted entirely to lowercase using JavaScript's native string lowering methods.
- Subsequent Tokens: Every word after the first is
transformed using Lodash's internal
upperFirstlogic. The first character of each word is converted to uppercase, while the remaining characters are normalized to lowercase. - 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:
- Token Extraction: Lodash identifies the word
segments, producing
['FOO', 'BAR', 'baz', '123']. The dashes, underscores, spaces, and the exclamation mark are omitted entirely. - 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).
- 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.