Lodash trimEnd Target Characters Explained
The Lodash _.trimEnd method is designed to remove
trailing characters from a string, helping developers clean up unwanted
padding or delimiters. By default, it targets all trailing whitespace
characters defined by the ECMAScript standard, including standard
spaces, tabs, and line breaks. However, it can also be configured to
target specific user-defined characters by supplying a secondary
argument.
Default Target: Whitespace Characters
When called with only a string argument—such as
_.trimEnd(string)—the function targets and strips trailing
whitespace. Lodash defines whitespace in accordance with ECMAScript
specifications, matching standard ASCII whitespace characters and
broader Unicode space separators.
Specifically, the default execution targets:
- Standard Space:
(\u0020) - Horizontal Tab:
\t(\u0009) - Line Feed (Newline):
\n(\u000A) - Carriage Return:
\r(\u000D) - Vertical Tab:
\v(\u000B) - Form Feed:
\f(\u000C) - Non-Breaking Space:
\u00A0 - Unicode Space Separators: Characters in the Unicode General Category "Zs" (such as en quad, em quad, thin space, ideographic space, etc.)
- Line and Paragraph Separators:
\u2028and\u2029 - Byte Order Mark (Zero Width No-Break Space):
\uFEFF
Any combination of these characters at the very end of the string will be iteratively stripped until a non-whitespace character is encountered.
Custom Target Characters
When a second argument is
passed—_.trimEnd(string, [chars])—Lodash stops targeting
whitespace and instead targets only the specific characters provided in
the chars parameter.
Key behaviors of custom character targeting include:
- Character Sets, Not Substrings: Lodash treats the
charsargument as a collection of individual characters rather than a single contiguous substring. For example,_.trimEnd('foo/\\', '/\\')removes both slashes from the end. - Order Independence: The characters can appear in
any order at the end of the string; Lodash will continue removing any
character that matches any character in the
charsargument until it hits an unlisted character. - Case Sensitivity: Targeted characters are strictly
case-sensitive. Specifying
'abc'will not strip'ABC'.