拼音搜索 拼音首字母搜索 (pinyin-match) js

  1. 下载插件 pinyin-match
 npm install pinyin-match --save 

这个插件支持简写和繁体两样;各自的包压缩后大小不一致:简体版27KB (gzip ≈ 19KB),繁体版86KB (gzip ≈ 60KB)

  1. 引用
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]
  1. 二次封装监测多次匹配(如果给如的搜索条件满足了一项则返回数组 否则 返回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

参考链接:

  1. pinyin-match官网
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
js-pinyin 是一个 JavaScript 拼音转换库,可以将中文转换成拼音,它可以帮助我们实现数组某字段拼音首字母排序。 首先,我们需要使用 js-pinyin 将中文转换成拼音,然后提取每个拼音首字母,最后按照首字母进行排序。 下面是一个示例代码: ```javascript // 引入 js-pinyin 库 import pinyin from 'js-pinyin'; // 假设我们有如下的数组 const arr = [ { name: '张三', age: 18 }, { name: '李四', age: 20 }, { name: '王五', age: 22 }, ]; // 将数组按照 name 字段的拼音首字母排序 arr.sort((a, b) => { const pinyinA = pinyin.getFullChars(a.name); // 获取 a 的拼音 const pinyinB = pinyin.getFullChars(b.name); // 获取 b 的拼音 const initialA = pinyinA.charAt(0); // 获取 a 的拼音首字母 const initialB = pinyinB.charAt(0); // 获取 b 的拼音首字母 if (initialA < initialB) { return -1; } if (initialA > initialB) { return 1; } return 0; }); console.log(arr); // 输出排序后的数组 ``` 在上面的代码中,我们先引入了 js-pinyin 库,然后定义了一个数组 arr,包含了一些对象,每个对象都有 name 和 age 两个字段。 接着,我们使用数组的 sort 方法进行排序,sort 方法的参数是一个函数,这个函数接受两个参数 a 和 b,分别表示数组中的两个元素。 在排序函数中,我们首先使用 pinyin.getFullChars 方法将 name 字段转换成拼音,然后使用 charAt(0) 方法获取拼音首字母,最后按照首字母进行比较,返回 -1、1 或 0,以确定两个元素的顺序。 最后,我们输出排序后的数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值