43 lines
1.3 KiB
JavaScript
43 lines
1.3 KiB
JavaScript
|
|
// pinyin.js - 拼音转换工具
|
|||
|
|
// src/utils/pinyin-utils.js
|
|||
|
|
import { pinyin } from 'pinyin-pro';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取文本的拼音首字母
|
|||
|
|
* @param {string} text - 要转换的文本
|
|||
|
|
* @returns {string} - 拼音首字母字符串
|
|||
|
|
*/
|
|||
|
|
export function getFirstLetter(text) {
|
|||
|
|
if (!text) return '';
|
|||
|
|
|
|||
|
|
// 获取拼音(不带音调,数组形式)
|
|||
|
|
const pinyinArray = pinyin(text, { toneType: "none", type: "array" });
|
|||
|
|
|
|||
|
|
// 提取每个拼音的首字母并连接
|
|||
|
|
return pinyinArray.map(word => word.charAt(0)).join('');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取文本的拼音全拼
|
|||
|
|
* @param {string} text - 要转换的文本
|
|||
|
|
* @returns {string} - 拼音全拼字符串
|
|||
|
|
*/
|
|||
|
|
export function getFullPinyin(text) {
|
|||
|
|
if (!text) return '';
|
|||
|
|
|
|||
|
|
// 获取拼音(不带音调,字符串形式)
|
|||
|
|
return pinyin(text, { toneType: "none" }).replace(/\s+/g, '');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 处理选项数据,添加拼音和首字母属性
|
|||
|
|
* @param {Array} options - 原始选项数组,每个元素包含id和text属性
|
|||
|
|
* @returns {Array} - 处理后的选项数组,每个元素包含pinyin和firstLetters属性
|
|||
|
|
*/
|
|||
|
|
export function processOptions(options) {
|
|||
|
|
return options.map(option => ({
|
|||
|
|
...option,
|
|||
|
|
pinyin: getFullPinyin(option.text),
|
|||
|
|
firstLetters: getFirstLetter(option.text)
|
|||
|
|
}));
|
|||
|
|
}
|