skip to Main Content

I have created a list in react that on key up the list can be filtered. My handler currently looks like this – but it only works on whole word matches and blanks on a result when the user starts typing or starts to add spaces to type the remaining words.

initialCommands: [
        {
          "label": "Order more plasters",
          "icon": ShoppingCart
        },
        {
          "label": "Book a meeting with my doctor",
          "icon": Bell
        }
      ]

enter image description here

  typeHandler(data){
    const regex = new RegExp(`\b(${data.command})\b`, "gi");

    const result = initialCommands.filter(function(item) {
      return item.label.match(regex);
    });

    this.setState({
      prunedCommands: result,
      prunedCommandsReady: true
    });    
  }

enter image description here

enter image description here

2

Answers


  1. I believe the regex needs to be updated. Try adding something like the following, note the period and asterisk.

    \b(${data.command}).*\b
    

    Whenever I’m messing with regex, I use this website. https://regex101.com/

    Login or Signup to reply.
  2. A very simple pure js filtering solution without using regular expressions.

    1. use startsWith to match string with the start position
    typeHandler(data){
      const command = `${data.command}`.toLowerCase().trim();
      const result = initialCommands.filter(obj => obj.label.toLowerCase().startsWith(command));
      // ...   
    }
    
    
    1. use includes to match strings without caring about position
    typeHandler(data){
      const command = `${data.command}`.toLowerCase().trim();
      const result = initialCommands.filter(obj => obj.label.toLowerCase().includes(command));
      // ...   
    }
    
    

    test

    // use `startsWith` to match string with the start position
    const typeHandler = (data) => {
      const command = `${data.command}`.toLowerCase().trim();
      return initialCommands.filter(obj => obj.label.toLowerCase().startsWith(command));
    }
    
    const initialCommands = [
      {
        "label": "Order more plasters",
      },
      {
        "label": "Book a meeting with my doctor",
      }
    ];
    
    const result = typeHandler({command: `Orde`});
    console.log(`result`, JSON.stringify(result, null, 2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search