前端拼音检索-【pinyin-match】

前端开发时,有时数据过多需要快速检索功能,常用的关键字匹配和拼音检索,发现一个不错的插件pinyin-match。

个人感觉应用场景为,数据量不是特别大,一次性加载到前端,由前端实现过滤。数据过大时还是后端完成比较好。

github地址:https://github.com/xmflswood/pinyin-match

示例:

let test = '123曾经沧海难为水除却巫山不是云'

PinyinMatch.match(test, '23曾'); // [1, 3]

PinyinMatch.match(test, 'cjc') // [3, 5]

PinyinMatch.match(test, 'cengjingcanghai') // [3, 6]

PinyinMatch.match(test, 'cengjingcangha') // [3, 6]

PinyinMatch.match(test, 'engjingcanghai') // false

PinyinMatch.match(test, 'zengjingcang') // [3, 5]

PinyinMatch.match(test, 'sdjkelwqf') // false

PinyinMatch.match(test, 'zengji ng cang') // [3, 5]

PinyinMatch.match(test, 'zengji ng cangsdjfkl') // false

PinyinMatch.match('   我 爱你 中   国   ', 'nzg') // [6, 12]

PinyinMatch.match('   我 爱你 中   国   ', '爱你中') // [5, 8]

PinyinMatch.match('發', 'fa') // [0, 0]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值