String casing utilities in JavaScript
- Published on
- • 2 mins read
I know that we suppose to have a library for this, but sometimes what we need is just a simple function to handle 1 or 2 cases
So here we go, just copy and paste the code below to your app.
Capitalize all words
/**
* Capitalize the first letter of all words in a string.
*
* @param str The string to capitalize.
* @returns The capitalized string.
* @example
* capitalizeAll('foo bar') // "Foo Bar"
*/
function capitalizeAll(str: string): string {
return capitalize(str.replace(/\s./g, ($1) => $1.toUpperCase()))
}
PascalCase
to plain text
/**
* Convert a pascal case string to plain text.
*
* @param str The string to convert.
* @returns The plain text.
* @example
* pascalCaseToPlainText('FooBar') // "foo bar"
*/
function pascalCaseToPlainText(str: string): string {
return str.replace(/[A-Z]/g, ($1) => ` ${$1.toLowerCase()}`).trim()
}
camelCase
to kebab-case
/**
* Convert a camel case string to kebab case.
* @param str The string to convert.
* @returns The kebab case string.
* @example
* camelCaseToKebabCase('fooBar') // "foo-bar"
*/
function camelCaseToKebabCase(str: string): string {
return str.replace(/[A-Z]/g, ($1) => `-${$1.toLowerCase()}`).trim()
}
kebab-case
to plain text
/**
* Convert a kebab case string to plain text.
*
* @param str The string to convert.
* @returns The plain text.
* @example
* kebabCaseToPlainText('foo-bar') // "foo bar"
*/
function kebabCaseToPlainText(str: string): string {
return str.replace(/-/g, ' ')
}
kebab-case
Plain text to /**
* Convert a plain text string to kebab case.
*
* @param str The string to convert.
* @returns The kebab case string.
* @example
* toKebabCase('hello World') // "hello-world"
*/
function toKebabCase(str: string): string {
return str.replace(/\s/g, '-').toLowerCase()
}
And many more in the future. Stay tuned!