Skip to content

Instantly share code, notes, and snippets.

@recca0120
Created December 13, 2024 11:18
Show Gist options
  • Save recca0120/8b95da658c933a80e0ad8ab03b6925e4 to your computer and use it in GitHub Desktop.
Save recca0120/8b95da658c933a80e0ad8ab03b6925e4 to your computer and use it in GitHub Desktop.
titleCase.ts
import { titleCase } from './utils';
describe('utils', () => {
describe('title case', () => {
it('NoNamespace -> No Namespace', () => {
expect(titleCase('NoNamespace')).toEqual('No Namespace');
});
it('noNamespace -> No Namespace', () => {
expect(titleCase('NoNamespace')).toEqual('No Namespace');
});
it('VSCode -> VSCode', () => {
expect(titleCase('VSCode')).toEqual('VSCode');
});
it('Recca0120 -> Recca0120', () => {
expect(titleCase('Recca0120')).toEqual('Recca0120');
});
it('Assertions2 -> Assertions2', () => {
expect(titleCase('Assertions2')).toEqual('Assertions2');
});
it('snake_case -> Snake Case', () => {
expect(titleCase('snake_case')).toEqual('Snake Case');
});
it('snake_case_AAA -> Snake Case AAA', () => {
expect(titleCase('snake_case_AAA')).toEqual('Snake Case AAA');
});
it('snake_case Aaa -> Snake Case Aaa', () => {
expect(titleCase('snake_case Aaa')).toEqual('Snake Case Aaa');
});
it('camelCase -> Camel Case', () => {
expect(titleCase('camelCase')).toEqual('Camel Case');
});
it('PascalCase -> Pascal Case', () => {
expect(titleCase('PascalCase')).toEqual('Pascal Case');
});
it('kebab-case -> Kebab-Case', () => {
expect(titleCase('kebab-case')).toEqual('Kebab Case');
});
it('This is an HTML element -> This Is An HTML Element', () => {
expect(titleCase('This is an HTML element')).toEqual('This Is An HTML Element');
});
});
});
export const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
export const uncapitalize = (str: string) => str.charAt(0).toLowerCase() + str.slice(1);
export const snakeCase = (str: string) => str.replace(/([a-z])([A-Z])/g, '$1_$2').replace(/[\s\-]+/g, '_').toLowerCase();
export const camelCase = (str: string) => str.toLowerCase().replace(/([-_ \s]+[a-z])/g, (group) => group.toUpperCase().replace(/[-_ \s]/g, ''));
export const titleCase = (str: string) => capitalize(str.replace(/([A-Z]+|[_\-\s]+([A-Z]+|[a-z]))/g, (_: string, matched: string) => {
return ' ' + matched.trim().replace(/[_\-]/, '').toUpperCase();
}).trim());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment