Skip to content

Commit

Permalink
Add toTitleCase() strring util
Browse files Browse the repository at this point in the history
  • Loading branch information
techniq committed Aug 19, 2023
1 parent b16a986 commit 70caaab
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/ninety-mayflies-grab.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-ux': patch
---

Add `toTitleCase()` strring util
17 changes: 17 additions & 0 deletions src/lib/utils/string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest';

import { toTitleCase } from './string';

describe('toTitleCase()', () => {
it('basic', () => {
const original = 'this is a test';
const expected = 'This is a Test';
expect(toTitleCase(original)).equal(expected);
});

it('basic', () => {
const original = 'A long time ago';
const expected = 'A Long Time Ago';
expect(toTitleCase(original)).equal(expected);
});
});
17 changes: 17 additions & 0 deletions src/lib/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ export function isUpperCase(str: string) {
return /^[A-Z]*$/.test(str);
}

/**
* Returns string with the first letter of each word converted to uppercase (and remainder as lowercase)
*/
export function toTitleCase(str: string, ignore = ['a', 'an', 'is', 'the']) {
return str
.toLowerCase()
.split(' ')
.map((word, index) => {
if (index > 0 && ignore.includes(word)) {
return word;
} else {
return word.charAt(0).toUpperCase() + word.slice(1);
}
})
.join(' ');
}

/**
* Generates a unique Id, with prefix if provided
*/
Expand Down

0 comments on commit 70caaab

Please sign in to comment.