---
heading: 'Casing utilities'
title: 'String casing utilities in JavaScript'
date: '2023-02-21'
icon: 'Typescript'
draft: false
summary: 'A various ready-to-use string casing utilities in Typescript.'
tags: ['javascript', 'typescript', 'string', 'casing', 'utilities']
---

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 <Twemoji emoji="man-shrugging" />

So here we go, just copy and paste the code below to your app.

### Capitalize all words

```ts
/**
 * 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

```ts
/**
 * 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`

```ts
/**
 * 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

```ts
/**
 * 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, ' ')
}
```

### Plain text to `kebab-case`

```ts
/**
 * 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!
