Converting strings to other cases (including "camelCase", "PascalCase", "snake_case", etc.) is a fairly common task, – yet I haven't found any case-related proposals, neither in tc39/proposals GitHub repo, nor here (probably because there are countless npm libraries to do this conversion?).
So, basically, the proposal is trivial: for some cases (to be discussed), adding case-related methods to primitive strings and string instances, – I can think of several of those (the identifiers are also not set in stone):
const string = "hello world";
string.toCamelCase(); // "helloWorld"
string.toPascalCase(); // "HelloWorld"
string.toKebabCase(); // "hello-world"
string.toSnakeCase(); // "hello_world"
string.toConstantCase(); // "HELLO_WORLD"
string.toTitleCase(); // "Hello World"
Or (to avoid using arbitrary namings, such as "kebab" or "snake") this can be a single function, a-la Intl
API, – but to me, this seems a bit over the top. If such a function is okay though, putting it statically on the String
constructor might be a good choice too:
String.prototype.toCase(params);
String.toCase(string[, params]);
const string = "what a lovely day";
string.toCase();
// "what a lovely day"
string.toCase({ match: "n + 1", separator: "", pattern: "Aa*" }); // camelCase
// "whatALovelyDay"
string.toCase({ match: "n", separator: "_", pattern: "A*"}); // CONSTANT_CASE
// "WHAT_A_LOVELY_DAY"
string.toCase({ match: "n", separator: " ", pattern: "A*" }); // Title Case
// "What A Lovely Day"
string.toCase({ match: "n", separator: " ", pattern: "(Aa)*" });
// "WhAt A LoVeLy DaY"
string.toCase(
{ match: "1 - n", separator: "@", pattern: "a*" }, // first and second words
{ match: "n + 2", separator: "-", pattern: "A*" }, // third and subsequent words
);
// "what@a LOVELY-DAY"
I'm a bit uncertain about how this would work with punctuation, whitespace characters, and other non-word characters, but I guess this can be derived from how .toLowerCase()
and .toUpperCase()
work?