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

What is causing the data not to react with the props in this particular scenario?

In addition to the central App.vue component, I have two other components - Rooms.vue and Desks.vue. When a swiper element in the Rooms.vue component is clicked, it triggers the opening of the Desks.vue component and emits the room object to App.vue. This ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

When you click, apply the hidden class to all the div elements

Is there a way to apply the .hide class to all .slide divs whenever the .option button is clicked? If so, how can I modify my JavaScript code so that all .slide divs receive the .hide class (if they don't already have it) upon clicking the .option bu ...

Displaying the combined total for each date

My goal is to calculate the total for each department without duplicates ( which is currently working ) and display all results based on the selected date. I intend to select a date using md-datepicker and then only display the total task time where the d ...

What is the best way to utilize JavaScript variables that are declared on index.html/index.jsp in Vue.js?

Just starting out with Vue.js and I recently finished developing a Vue.js app using the terminal. I then deployed it on a Java web application and noticed that everything works fine when running it as is. However, I now need to pass a csrftoken to my Vu ...

Troubleshooting: Why is VueJS computed filter function failing to work

Currently, I am working on incorporating the functionality outlined in this Vuejs Search filter article. However, the function inside the computed property is not working as expected, and it's not even logging anything. Below is a snippet of my code: ...

Should we make it a routine to include shared sass variables in each vue component for better practice?

Within my Vue application, there are numerous components that rely on shared variables like colors. I'm considering having each component import a global "variables.scss" file. Would this approach have any adverse effects? ...

The process of exporting and utilizing models in Sequelize

When working on my node.js project with sequelize, I encountered a challenge of exporting and using table models in another file. I typically save table models in a folder, for instance Profile.js. module.exports = (sequelize, DataTypes) => sequelize.d ...

Is it possible to create a dynamic template in Angular using external sources?

My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives. I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive: var AngularHelper ...

Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someo ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

Utilizing Stripe for Payment Processing

I'm encountering a problem with getting Stripe charging to function properly. Despite having manually loaded Composer since it wouldn't install, I am not receiving any PHP errors and the token creation is running smoothly. There don't seem t ...

Confirming if the value is an array using jQuery

Currently, I have a list of elements with various types associated with them. My goal is to identify specific text within these types and hide only those types that do not contain the desired text, leaving the rest unaffected. The structure looks like thi ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Retrieving the original state value after updating it with data from local storage

Incorporating the react-timer-hook package into my next.js project has allowed me to showcase a timer, as illustrated in the screenshot below: https://i.stack.imgur.com/ghkEZ.png The challenge now lies in persisting the elapsed time of this timer in loca ...

Expand parent view slot within RouterLink component

I have set up a Vue route with a parent view and two child views ./route/index.ts const router = createRouter({ routes: [ { path: '/dataset/:dataset_name', component: DatasetItemView, children: [ ...

Encountering a problem while trying to launch the development server for a React application using the npm-start

I followed the steps to create a react application using npx create-react-app myapp, but when I use npm start, it fails to start a developer server. Even after trying to reinstall the node_modules, the issue persists. I am using the latest versions of Reac ...

Techniques for implementing a PHP base_url() function in a JavaScript file

I need to pass base_url from the Book Controller to the book.js file This is the function within book.js function loadPage(page, pageElement) { // Create an image element var img = $('<img />'); img.mousedown(function(e) { ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...

using angularjs to dynamically apply css styles

Below is the input I have: The HTML code is shown below: <input type="number" ng-class="{negative: amount < 0}" ng-model="amount"/> This is the corresponding CSS code: .negative { color: red; } If the amount is positive, no specif ...