Files
knowai/utils/string.ts
tobegold574 6a81b7bb13
Some checks reported errors
continuous-integration/drone/push Build was killed
feat(image): 新建 knowai-core:1.0.0 镜像并完成推送
- 搭建 api、auth、utils 等逻辑模块
- 通过 tsc、eslint、vitest 测试验证

BREAKING CHANGE: 新镜像分支
2025-11-10 20:20:25 +08:00

91 lines
2.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 字符串格式化工具
export const stringUtils = {
// 截断字符串并添加省略号
truncate: (str: string, maxLength: number, suffix = '...'): string => {
if (str.length<=maxLength) return str;
// 计算截断位置,确保结果不超过最大长度
const truncateLength = maxLength - suffix.length;
return str.substring(0, truncateLength) + suffix;
},
// 首字母大写
capitalize: (str: string): string => {
if (!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1);
},
// 驼峰命名转换
toCamelCase: (str: string): string => {
if (!str) return '';
// 先检查字符串是否已经是驼峰命名(首字母小写,无分隔符)
const isAlreadyCamelCase = /^[a-z][a-zA-Z0-9]*$/.test(str);
if (isAlreadyCamelCase) {
return str;
}
// 处理短横线、下划线和空格分隔的情况
return str
// 先将整个字符串转换为小写
.toLowerCase()
// 将所有分隔符后的首字母大写
.replace(/[-_\s]+(.)/g, (_, char) => char ? char.toUpperCase() : '');
},
// 短横线命名转换
toKebabCase: (str: string): string => {
if (!str) return '';
return str // 先将下划线和空格替换为短横线
.replace(/[_\s]+/g, '-')
// 处理驼峰命名:在小写字母或数字后跟大写字母时插入短横线
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
// 处理连续大写字母的情况如HTMLParser -> html-parser
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
// 转换为全小写
.toLowerCase();
},
// 下划线命名转换
toSnakeCase: (str: string): string => {
if (!str) return '';
return str // 先将短横线和空格替换为下划线
.replace(/[-\s]+/g, '_')
// 处理驼峰命名:在小写字母或数字后跟大写字母时插入下划线
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
// 处理连续大写字母的情况如HTMLParser -> html_parser
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
// 转换为全小写
.toLowerCase();
},
// 转义HTML特殊字符
escapeHtml: (text: string): string => {
const map: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, (m) => map[m] || m);
},
// 生成随机字符串
randomString: (length = 10): string => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
},
// 检查是否为空字符串(包括只有空白字符的字符串)
isEmpty: (str: string | null | undefined): boolean => {
return !str || str.trim().length === 0;
}
};