Develop a search feature that automatically filters out special characters when searching through a

I am currently developing a Vue-Vuetify application with a PHP backend. I have a list of contacts that include first names, last names, and other details that are not relevant at the moment. My main query is how to search through this list while disregarding any special characters. Let me provide an example: Name: Janko Hraško (in my language, we use names with special characters like ľščťžýáí...). Currently, when I search in the list, I can only search by either first name or last name. For instance, if I type "Janko," I will find the person, and similarly for "Hraško." My first question is, is there a way to merge the two together? For example: If I type "Jan" (the person will appear, but there may be multiple people with the same starting name), and then I enter a space followed by "Hra" (to narrow down to just one person). Essentially, what I'm trying to achieve is a combined search functionality for both first and last names without having to input the full name. Secondly, how can I disregard special characters? Currently, searching for "Hrasko" yields no results, but as soon as I enter "Hraško," the specific person shows up. Is it feasible to ignore all special characters during the search process? Like being able to find "Hrasko" even if the actual name includes special characters like "Hraško"?

Below is a snippet of my code (Vue.app):

computed: {
filteredContacts (){
  if(this.search){
  return this.contact_list.filter((item)=>{
    return item.firstname.toLowerCase().startsWith(this.search) || item.lastname.toLowerCase().startsWith(this.search) ||
        item.firstname.startsWith(this.search) || item.lastname.startsWith(this.search);
  })
  }else{
    return this.resources;
  }
}

Any assistance would be greatly appreciated! Thank you.

Answer №1

My understanding is that you are looking to search for users by their first and last names, and I have devised a solution as follows:

You can create an algorithm to identify multiple normalized words within an array of normalized texts.

  1. In your data, define the information you want to search and create an array of objects

  2. Normalize the search field input and convert it into a regex pattern

  3. Then, filter your array of users by converting the data from each object in the array into a normalized string and matching it with your regex pattern

This approach addresses the problem at hand. If anyone has a more efficient solution, I am open to suggestions. Below is an example for reference; if it does not work, you can also access the code snippet on CodePen [https://codepen.io/jorgehn1995/pen/BawJbwX][1]

new Vue({
  el: "#app",
  data() {
    return {
    /**
    *1 DEFINES THE DATA 
    **/
      search: "",
      users: [
        {name:"Janko", lastName:"Hraško"},
        {name:"Janko", lastName:"Hrašdo"},
        {name:"Jando", lastName:"Hro"},
        { name: "John", lastName: "Dúe" },
        { name: "Jessie", lastName: "Dös" }
      ]
    };
  },
  computed: {
    searchUsers() {
      if(this.search=="") return this.users;
      /**
       *2 THIS CODE GENERATE THE REGEX
       **/
      let searchData = this.search
        .normalize("NFD")
        .replace(/[\u0300-\u036f]/g, "")
        .toLowerCase()
        .replace(/ /g, ")(?=.*");
      searchData = "(?=.*" + searchData + ").*";
      let regexToSearch = new RegExp(searchData, "gi");

      /**
       *3 THIS CODE GENERATES A ARRAY OF STRINGS
       *WHERE THE PREVIOUS CODE WILL BE SEARCHED
       **/

      return this.users.filter((e) => {
        return (e.name + " " + e.lastName)
          .toString()
          .normalize("NFD")
          .replace(/[\u0300-\u036f]/g, "")
          .toLowerCase()
          .match(regexToSearch);
      });
    }
  }
});
.ma{
 margin:25px;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify/dist/vuetify.min.css">

<div id="app">
  <v-container style="magin-bottom:50px;">
    <v-row dense>
      <v-col cols="12" sm="4">
        <v-card class="ma">
          <v-card-text>
            Source Data
          </v-card-text>
          <v-card-text>
            {{users}}
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" sm="4">
        <v-card class="ma">
          <v-card-text>
            Search Field
          </v-card-text>
          <v-card-text>
            <v-text-field label="Search" v-model="search" filled></v-text-field>
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" sm="4">
        <v-card class="ma">
          <v-card-text>
            Search Results
          </v-card-text>
          <v-card-text>
            {{searchUsers}}
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The scope of a JS array is being lost in Firebase

The Firebase data structure looks like this: -users --demo1 ---conid:1 -election --election1 ---conRegex:1 --election2 ---conRegex:1 Here is the code to retrieve election1 and election2: var conid; var conRegex; var electionArr = []; if(uidA ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID. var status = var status = item.down().next().innerHtml(); if(status == "test") { var c = 'item_'+i ; c.style.backgroundColor = 'rgb(255, 125, 115)'; //'ite ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Is it possible for jQuery to create two separate variables with identical names?

When it comes to declaring variables in jQuery, you have 2 different options: The jQuery method The JavaScript method Are these two statements equivalent: $variable = "string"; And: var variable = "string"; Or do they create separate variables? ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

Steps to indicate a cucumber test as incomplete using a callback function in a node environment

Can a cucumber test in Node be flagged as pending to prevent automated test failures while still specifying upcoming features? module.exports = function() { this.Given(/^Scenario for an upcoming feature$/, function(callback) { callback(); } ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...

Upon reloading the page, the Vue getter may sometimes retrieve an undefined value

My blog contains various posts. Clicking on a preview will direct you to the post page. Within the post page, I utilize a getter function to display the correct post (using the find method to return object.name which matches the object in the array). cons ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

Sending a object as an argument to a function

Could someone please help me understand the purpose of passing an object as a function parameter? I have been trying to learn Next.js and they frequently use this method in their code. If anyone could provide a brief explanation of why this is done, it wo ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Utilizing multiple API calls to initiate JSON data and seamlessly integrate it across the entire system

I am currently developing a project that utilizes Vue.js and Laravel for implementation. The project is focused on academia and consists of units, lessons, and activities, all interrelated. Each unit contains multiple lessons, and each lesson contains mult ...

What is the most effective way to divide input elements into an array in Angular?

How can I bind an input value to an ng-model as an array? For example, if I enter one, two, three, I want the resulting model to be [ "one","two","three" ]. Currently, this is my approach: <input type="text" ng-model="string" ng-change="convertToArra ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...