Recently, I needed to write a search function when I was working on a project. At the beginning, I thought this function was very powerful and awesome, but when I did it myself, I felt a little confused, but after I started it, I felt ok, haha. Here’s how I implemented the search feature. I hope it helps a kid like me.

Accurate search

** Core idea: ** Matches the string entered by the user as a whole with each item in the array, and saves the matching items.

Let’s have a look at the renderings firstThe main thing that’s used hereJavaScriptA string ofindexOf()Method – returns the first occurrence of a specified string value in the string, or -1 if none exists.

It is important to note that the 'indexOf()' method is case-sensitive! Arrays also have an 'indexOf()' methodCopy the code

Below is the complete code for the above example, although the data will not be as simple in actual development. We use Vue + Element here

implementation

<template>
  <div class="wrapper">
    <el-input
      clearable
      placeholder="Please enter"
      suffix-icon="el-icon-search"
      v-model="searchMsg"
      size="mini"
      @input="handleSearch(searchMsg)"
    ></el-input>
    <el-checkbox-group v-model="checkList">
      <div v-for="(item, index) in filterMsg" :key="index">
        <el-checkbox :label="item">{{ item.name }}</el-checkbox>
      </div>
    </el-checkbox-group>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchMsg: "".checkList: [].filterMsg: []}; },mounted() {
    this.allMsg = [
      { name: "myhua".id: 1 },
      { name: "mp3".id: 2 },
      { name: "hello".id: 3 },
      { name: "world".id: 4 },
      { name: "warm weather".id: 5 },
      { name: "m3".id: 6 },
      { name: "hahaha".id: 7}];this.filterMsg = this.allMsg;
  },
  methods: {
    // Search methods
    handleSearch(queryString) {
      this.filterMsg = [];
      this.allMsg.map(item= > {
        if(item.name.indexOf(queryString) ! = = -1) {
          this.filterMsg.push(item); }}); }}};</script>
Copy the code

The search() method for strings can do the same here, being case-sensitive

It is recommended to use includes to make it more semantic. If I am a little lazy, I will not change it here

Fuzzy search

** Core idea: ** Split the string entered by the user to match each item in the array, and save the matching one. To do this, you need regular expressions

Effect:

implementation

// Same as above
handleSearch(queryString) {
  let queryStringArr = queryString.split("");
  let str = "(. *?) ";
  this.filterMsg = [];
  let regStr = str + queryStringArr.join(str) + str;
  let reg = RegExp(regStr, "i"); // Using mh as an example, the generated regular expression is /(.*?). m(.*?) h(.*?) /i
  this.allMsg.map(item= > {
    if (reg.test(item.name)) {
      this.filterMsg.push(item); }}); }Copy the code

Pinyin search

Core idea: first get the pinyin of Chinese characters, and then match it to get the pinyin of Chinese characters. A brief introduction to the use of pinyin packets

import py from "pinyin";
py("Center"); // [['zhōng'], ['xīn']
py("Center", {
  heteronym: true               // Configure some Settings to enable polyphonic mode
});                            // [['zh ', 'zhong'], ['xīn']
Copy the code

If you are interested in learning about the conversion of Chinese characters to Pinyin, you can read this article300 lines of JavaScript to convert Chinese characters to pinyinHowever, the package written in this article can solve the problem of polyphonics

Effect:

implementation

// Same as above
import py from "pinyin";
mounted() {
    this.allMsg = [
      { name: "Xue Zhiqian".id: 1 },
      { name: "Wallace Huo".id: 2 },
      { name: "CAI Xukun".id: 3 },
      { name: "Brief".id: 4 },
      { name: "Nonsense".id: 5}];this.filterMsg = this.allMsg;
  },
methods: {
  handleSearch(queryString) {
    let queryStringArr = queryString.split("");
    let str = "(. *?) ";
    let regStr = str + queryStringArr.join(str) + str;
    let reg = RegExp(regStr, "i");
    this.filterMsg = [];
    console.log(reg);
    this.allMsg.map(item= > {
      // Get the pinyin of Chinese characters and flatten them
      let pyArr = py(item.name, {
        style: py.STYLE_NORMAL // Set pinyin style to normal style (without tones),
      }).flat();
      let pyStr = pyArr.join("");
      if (reg.test(pyStr)) {
        this.filterMsg.push(item); }}); }}Copy the code

The last

Different scenarios have different requirements. You may need to use one of the above methods, or you may need to combine the three methods mentioned above to form a comprehensive search. Also – for a better experience, we should sort our search results according to demand and highlight keywords. Here I will not show you 😁 as for the performance of the above three ways, I feel good, with the line. I hope an experienced guy can give me some Pointers