Skip to content

capitalize() keeps full uppercase strings instead of normalizing case #9

@OscarHenry

Description

@OscarHenry

Description

In the latest version of stringr, the capitalize() extension behaves unexpectedly when the input string is already in full uppercase.

Example:

"HELLO".capitalize()

Current output:

HELLO

Expected output:

Hello

The method currently uppercases the first character but leaves the rest of the string unchanged. This causes fully-uppercase inputs to remain fully uppercase, which defeats the purpose of a typical capitalize operation (first letter uppercase, remaining letters lowercase).


Root cause

In case.dart, the current implementation is:

false => isEmpty ? '' : this[0].toUpperCase() + substring(1),

Here, substring(1) preserves the original casing of the remainder of the string.


Proposed fix

Lowercase the remainder explicitly:

false => isEmpty
    ? ''
    : this[0].toUpperCase() + substring(1).toLowerCase(),

This produces consistent behavior:

"HELLO".capitalize() // Hello
"hello".capitalize() // Hello
"HeLLo".capitalize() // Hello

Why this matters

Most capitalize implementations across ecosystems normalize the string to:

Uppercase first letter + lowercase remainder

Current behavior is surprising and inconsistent, especially when working with API responses or legacy data that may arrive in all caps.


Happy to submit a PR if this approach is acceptable 👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions