以下是一些在 TypeScript 中处理字符串大小写的实用工具函数。
capitalizeAll
将字符串中所有单词的首字母大写。
/**
* 将字符串中所有单词的首字母大写
* @param str 要处理的字符串
* @returns 处理后的字符串
* @example
* capitalizeAll('hello world') // 'Hello World'
*/
export function capitalizeAll(str: string): string {
return str
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}
pascalCaseToPlainText
将 PascalCase 字符串转换为普通文本。
/**
* 将 PascalCase 字符串转换为普通文本
* @param str 要处理的字符串
* @returns 处理后的字符串
* @example
* pascalCaseToPlainText('HelloWorld') // 'Hello World'
*/
export function pascalCaseToPlainText(str: string): string {
return str.replace(/([A-Z])/g, ' $1').trim()
}
camelCaseToKebabCase
将 camelCase 字符串转换为 kebab-case。
/**
* 将 camelCase 字符串转换为 kebab-case
* @param str 要处理的字符串
* @returns 处理后的字符串
* @example
* camelCaseToKebabCase('helloWorld') // 'hello-world'
*/
export function camelCaseToKebabCase(str: string): string {
return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase()
}
kebabCaseToPlainText
将 kebab-case 字符串转换为普通文本。
/**
* 将 kebab-case 字符串转换为普通文本
* @param str 要处理的字符串
* @returns 处理后的字符串
* @example
* kebabCaseToPlainText('hello-world') // 'Hello World'
*/
export function kebabCaseToPlainText(str: string): string {
return str
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}
toKebabCase
将普通文本字符串转换为 kebab-case。
/**
* 将普通文本字符串转换为 kebab-case
* @param str 要处理的字符串
* @returns 处理后的字符串
* @example
* toKebabCase('Hello World') // 'hello-world'
*/
export function toKebabCase(str: string): string {
return str
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.toLowerCase()
}
更多工具函数将在未来添加。