85 lines
2.6 KiB
JavaScript
85 lines
2.6 KiB
JavaScript
export function parseToWords(text) {
|
|
if (!text || !text.trim()) {
|
|
return []
|
|
}
|
|
|
|
let processed = text.trim()
|
|
|
|
// 处理各种分隔符:空格、下划线、横线、驼峰
|
|
// 1. 先处理连续大写字母的情况:XMLHttpRequest -> XML Http Request
|
|
processed = processed.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
|
|
|
|
// 2. 先处理数字和字母的边界(必须在驼峰处理之前)
|
|
// 2.1 字母+数字+字母:temp2Detail -> temp 2 Detail
|
|
processed = processed.replace(/([a-zA-Z])(\d+)([a-zA-Z])/g, '$1 $2 $3')
|
|
// 2.2 字母+数字(后面跟着分隔符或结尾,但不是字母):item2 -> item 2
|
|
// 注意:这里不匹配后面跟着字母的情况(已由2.1处理)
|
|
processed = processed.replace(/([a-zA-Z])(\d+)(?=[_\-\s]|$)/g, '$1 $2')
|
|
// 2.3 数字+字母(在单词开头或前面是分隔符):2item -> 2 item
|
|
processed = processed.replace(/(\d+)([a-zA-Z])/g, '$1 $2')
|
|
|
|
// 3. 处理驼峰:camelCase -> camel Case(在数字处理之后)
|
|
processed = processed.replace(/([a-z])([A-Z])/g, '$1 $2')
|
|
|
|
// 4. 统一分隔符:下划线、横线、空格统一为空格
|
|
processed = processed.replace(/[_\-\s]+/g, ' ')
|
|
|
|
// 5. 分割并处理
|
|
let words = processed
|
|
.split(' ')
|
|
.filter(word => word.length > 0)
|
|
.map(word => {
|
|
// 转换为小写,保留字母和数字
|
|
return word.toLowerCase()
|
|
})
|
|
.filter(word => word.length > 0) // 允许纯数字
|
|
|
|
return words
|
|
}
|
|
|
|
// 转换单词首字母为大写(处理数字情况)
|
|
export function capitalizeWord(word) {
|
|
if (!word) return ''
|
|
// 如果单词是纯数字,直接返回
|
|
if (/^\d+$/.test(word)) return word
|
|
// 否则首字母大写
|
|
return word.charAt(0).toUpperCase() + word.slice(1)
|
|
}
|
|
|
|
// 转换为小驼峰 (camelCase)
|
|
export function toCamelCase(words) {
|
|
if (words.length === 0) return ''
|
|
|
|
const firstWord = words[0]
|
|
const restWords = words.slice(1).map(word => capitalizeWord(word))
|
|
|
|
return firstWord + restWords.join('')
|
|
}
|
|
|
|
// 转换为大驼峰 (PascalCase)
|
|
export function toPascalCase(words) {
|
|
if (words.length === 0) return ''
|
|
|
|
return words.map(word => capitalizeWord(word)).join('')
|
|
}
|
|
|
|
// 转换为下划线 (snake_case)
|
|
export function toSnakeCase(words) {
|
|
if (words.length === 0) return ''
|
|
|
|
return words.join('_')
|
|
}
|
|
|
|
// 转换为横线 (kebab-case)
|
|
export function toKebabCase(words) {
|
|
if (words.length === 0) return ''
|
|
|
|
return words.join('-')
|
|
}
|
|
|
|
// 转换为常量 (CONSTANT_CASE)
|
|
export function toConstantCase(words) {
|
|
if (words.length === 0) return ''
|
|
|
|
return words.map(word => word.toUpperCase()).join('_')
|
|
} |