[str] add capitalize and titlecase

This commit is contained in:
Chris Wanstrath 2025-12-10 11:26:04 -08:00
parent d8c63e7981
commit 03a83abfbb
3 changed files with 32 additions and 0 deletions

View File

@ -28,6 +28,16 @@ export const str = {
}, },
'pad-start': (str: string, length: number, pad: string = ' ') => String(str ?? '').padStart(length, pad), 'pad-start': (str: string, length: number, pad: string = ' ') => String(str ?? '').padStart(length, pad),
'pad-end': (str: string, length: number, pad: string = ' ') => String(str ?? '').padEnd(length, pad), 'pad-end': (str: string, length: number, pad: string = ' ') => String(str ?? '').padEnd(length, pad),
capitalize: (str: string) => {
const s = String(str ?? '')
return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()
},
titlecase: (s: string) => {
return String(s ?? '')
.split(' ')
.map(str.capitalize)
.join(' ')
},
lines: (str: string) => String(str ?? '').split('\n'), lines: (str: string) => String(str ?? '').split('\n'),
chars: (str: string) => String(str ?? '').split(''), chars: (str: string) => String(str ?? '').split(''),

View File

@ -16,6 +16,18 @@ describe('string operations', () => {
await expect(`str.trim '\\n\\thello\\t\\n'`).toEvaluateTo('hello') await expect(`str.trim '\\n\\thello\\t\\n'`).toEvaluateTo('hello')
}) })
test('capitalize makes first char uppercase', async () => {
await expect(`str.capitalize 'hello'`).toEvaluateTo('Hello')
await expect(`str.capitalize 'HELLO'`).toEvaluateTo('Hello')
await expect(`str.capitalize 'hello world'`).toEvaluateTo('Hello world')
})
test('titlecase capitalizes each word', async () => {
await expect(`str.titlecase 'hello world'`).toEvaluateTo('Hello World')
await expect(`str.titlecase 'HELLO WORLD'`).toEvaluateTo('Hello World')
await expect(`str.titlecase 'the quick brown fox'`).toEvaluateTo('The Quick Brown Fox')
})
test('split divides string by separator', async () => { test('split divides string by separator', async () => {
await expect(`str.split 'a,b,c' ','`).toEvaluateTo(['a', 'b', 'c']) await expect(`str.split 'a,b,c' ','`).toEvaluateTo(['a', 'b', 'c'])
await expect(`str.split 'hello' ''`).toEvaluateTo(['h', 'e', 'l', 'l', 'o']) await expect(`str.split 'hello' ''`).toEvaluateTo(['h', 'e', 'l', 'l', 'o'])

View File

@ -739,6 +739,16 @@ export const completions = {
"pad" "pad"
] ]
}, },
"capitalize": {
"params": [
"str"
]
},
"titlecase": {
"params": [
"s"
]
},
"lines": { "lines": {
"params": [ "params": [
"str" "str"