How Lodash _.trim Handles Dynamic Newline Variables
Lodash’s _.trim function dynamically evaluates newline
variables and whitespace markers by resolving string boundaries through
a combination of Unicode-aware character parsing, internal boundary
index matching, and regular expression fallbacks. When dynamic variables
representing newlines—such as \n (Line Feed, U+000A),
\r (Carriage Return, U+000D), or explicit carriage-return
line-feed combinations—are supplied either as default whitespace or
custom character arguments, Lodash decomposes these sequences into
discrete Unicode symbols and scans the target string from both ends.
This mechanism avoids erratic regex recompilation, accurately handles
multi-byte line separators, and strips trailing and leading boundary
markers safely and efficiently.
Default Whitespace Resolution
When _.trim is invoked with a single argument, it relies
on its internal baseTrim implementation. In standard Lodash
architecture, whitespace is categorized using a predefined regular
expression pattern that encapsulates standard ASCII whitespace and
extended Unicode whitespace definitions:
\u0020(Space)\u0009(Horizontal Tab)\u000A(Line Feed)\u000B(Vertical Tab)\u000C(Form Feed)\u000D(Carriage Return)- Unicode line breaks such as
\u2028(Line Separator) and\u2029(Paragraph Separator)
If a dynamic variable containing unescaped or evaluated newline
characters is part of the string, the runtime evaluates them into their
native character codes before baseTrim processes them. The
internal regular expression matches leading and trailing occurrences of
any character within this set and removes them using
String.prototype.replace.
Custom Dynamic Newline Variables as Arguments
When dynamic variables representing newlines are explicitly passed to
the secondary chars parameter (e.g.,
_.trim(str, newlineVar)), Lodash branches away from
standard regular expression trimming to avoid ReDoS (Regular Expression
Denial of Service) risks and escaping bugs.
Instead, the library processes the dynamic argument through
charsStartIndex and charsEndIndex using the
following sequence:
- Symbol Decomposition via
stringToArray: Lodash converts both the target string and the custom delimiter variable into arrays of individual symbols using an internalstringToArrayutility. This ensures that composite newline variations (such as\r\n) and surrogate pairs are treated as exact atomic units rather than malformed code units. - Index Forward Scanning
(
charsStartIndex): An index pointer starts at0and increments along the target string array. At each step, it checks if the current character code matches any character present in the dynamic delimiters array. The search halts the moment a character outside the delimiter array is encountered. - Index Reverse Scanning
(
charsEndIndex): A secondary index begins at the end of the array (length - 1) and decrements backward, applying the same membership check. - Subsegment Slicing: Once both indices are
established, Lodash extracts the remaining string using
baseSlice.
Structural Handling of Encoded and Compound Newlines
When dynamic variables contain compound or explicitly encoded representations:
- Raw Evaluated Newlines (
"\r\n"): Lodash decomposes the variable into its component character set['\r', '\n']. Because matching incharsStartIndexandcharsEndIndexlooks up individual character membership within the set, the sequence order of\rand\nin the delimiter variable does not impede its ability to peel off any sequential permutation of carriage returns and line feeds at the string boundaries. - Escaped Literal Markers (
"\\n"): If a variable contains an escaped literal string (a backslash followed by the charactern) rather than a native newline control code, Lodash does not convert it into a line break. It parses the literal\(U+005C) andn(U+006E) as distinct entries in the delimiter array, matching and stripping only matching literal text sequences at the target string's edges.
This decoupled boundary-scanning architecture allows
_.trim to handle dynamic newline markers with uniform
algorithmic predictability across variable encodings without relying on
runtime regex generation.