collect-system/packages/utils/src/string-utils.ts

80 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-02-05 15:10:40 +08:00
/**
*
*
*/
/**
*
*/
export const isEmptyOrWhitespace = (str: string): boolean => {
return !str || str.trim().length === 0;
};
/**
*
*/
export const capitalize = (str: string): string => {
if (!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1);
};
/**
* (camelCase)
*/
export const toCamelCase = (str: string): string => {
return str
.toLowerCase()
.replace(/[-_ ]+(\w)/g, (_, group: string) => group.toUpperCase());
};
/**
* (snake_case)
*/
export const toSnakeCase = (str: string): string => {
return str
.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
.replace(/[\s\-]+/g, '_')
.replace(/^_/, '')
.toLowerCase();
};
/**
* (kebab-case)
*/
export const toKebabCase = (str: string): string => {
return str
.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)
.replace(/[\s_]+/g, '-')
.replace(/^-/, '')
.toLowerCase();
};
/**
* 使 "..."
*/
export const truncate = (str: string, length: number): string => {
if (str.length <= length) return str;
return str.slice(0, length) + '...';
};
/**
*
*/
export const charFrequency = (str: string): Record<string, number> => {
return str.split('').reduce((acc: Record<string, number>, char: string) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
};
/**
* JSON
*/
export const isValidJSON = (str: string): boolean => {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
};