- 下载插件 pinyin-match
npm install pinyin-match --save
这个插件支持简写和繁体两样;各自的包压缩后大小不一致:简体版27KB (gzip ≈ 19KB),繁体版86KB (gzip ≈ 60KB)
- 引用
import Pinyin from 'pinyin-match';
const str = '熬夜修仙冠军'
Pinyin.match(str, 'ay'); // [0, 1]
Pinyin.match(str, 'sdfsfdfsdfsdfssdf'); // false
Pinyin.match(str, '熬夜修'); // [0, 2]
Pinyin.match(str, 'ay'); // [0, 1]
除了以上常规的还有分辨空格的情况
import Pinyin from 'pinyin-match';
Pinyin.match(' 熬 夜 修 仙 冠 军', 'ay'); // [1, 4]
- 二次封装监测多次匹配(如果给如的搜索条件满足了一项则返回数组 否则 返回false;常用于输入搜索匹配)
utils.js
// 根据拼音过滤;参数: 以逗号形式单个分开传 filterPinYin('这是你输入的拼音', '这里及后面是你最终 判断的字符串', 'adfas', '2312')
// 如果给如的搜索条件满足了一项则 返回数组 否则 返回false
export const filterPinYin = (search, ...val) => val.reduce((cur, val) => cur || Pinyin.match(val, search), false);
a.js
filterPinYin('aoye', ' 熬 夜 修 仙 冠 军', '熬夜的王者', '熬爷在此', 'ces') // [1, 4]
filterPinYin('aoye', 'ces') // false
filterPinYin('aoye', ' 熬 夜 修 仙 冠 军', '熬夜的王者', '熬爷在此', 'ces') && console.log('test true') // test true
参考链接: