Enhance your search experience with Vue.js by highlighting important keywords across multiple search

I'm working on implementing a search feature that will bold the matching parts. For example, if I have the name 'John' and search for 'Jo Joh' in the same string, I want it to bold the part of 'John' that has the most matches, so it should display as John.

Here's what I have so far, but I'm running into an issue with the error message "error during evaluation" in my Vue Tools debugger.

computed: {
    bold: function () {
        var compare = [];
        var word = 'john';
        var array = ['jo', 'joh'];

        for (var i = 0; i < array.length; i++) {

            if (word.contains(array[i])) {
                compare[i] = array[i];
            }
        }
        var maxWord = compare[0];
        for (var i = 0; i < compare.length - 1; i++) {
            if (maxWord.length < compare[i].length) {
                maxWord = compare[i];
            }
        }
        return word.toString().replace(maxWord, '<strong>' + maxWord + '</strong>');
    }
}

Answer №1

Feel free to take a look at this example. Customize the search input to suit your needs.

Here is a method called boldString that converts strings:

function boldString(str, find){
    var re = new RegExp(find, 'g');
    return str.replace(re, '<b>'+find+'</b>');
}

You can loop through the array in this way:

function search(input){
  var arr = ["john", "doe"];
  var res = "";
  var i = 0;
  while(i < arr.length) {
    res += boldString(arr[i], input);
    res += " "; 
    i++; 
  }
  return res;
}

I trust this information proves useful!

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

Transforming a two-digit year into a four-digit year

Our entry form provides users with a calendar drop-down option, but they are also able to manually type in dates. We recently discovered that if someone enters a 2-digit year, it automatically changes to 1912 instead of 2012 (as dates cannot be in the past ...

Creating Varied Results Depending on State Values

I'm in the process of developing a quiz system where different selections lead to distinct outcomes, but I'm facing an issue where the output remains the same. What might be causing this problem? As an example, a user chooses between button 1 an ...

Using mapGetters with both modules and root getters simultaneously: A comprehensive guide

When using mapGetters in Vuex, I can easily call getters from a single root or module. For example, if I have a getter called firstRootGetter in the store/index.js, I would use ...mapGetters(['firstRootGetter']) in my Vue component. However, thi ...

Saving the current date and time in PHP and JS to persist even after the browser has been closed

I am currently facing a situation where I can click on an image and it will display a new image. In the previous grid-item, it shows the day and time I clicked on it. What I want to achieve is to have this functionality persist even after closing and reop ...

What are the steps for leveraging a proxy with NodeJS and Selenium?

While researching the topic on proxies in the documentation, I came across a method to set up a proxy while building a driver like this: var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .setProxy(proxy.manual ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

Encountering Difficulties Setting Variable in Vue

Recently delving into the world of VueJS & Tailwind, I am faced with a steep learning curve as I navigate npm for the first time. Within my code below lies a mixture of Tailwind and Headless UI that is almost complete, except for one nagging error message ...

Tips for choosing one specific element among multiple elements in cheerio nodejs

Currently, I'm attempting to extract links from a webpage. However, the issue I'm encountering is that I need to extract href from anchor tags, but they contain multiple tags with no class within them. The structure appears as follows. <div c ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

Troubleshooting: The issue of Vue JS not successfully navigating between web

After countless attempts, I am still struggling to get my Firebase login function to appropriately switch the component upon signing in. I urgently need assistance with configuring my router to seamlessly transition to the next page once the sign-in proces ...

Guide to using the ng-click function in Angular to set focus on the input in the last row of a table

I am in the process of developing a task management application and I am looking to implement a specific feature: Upon clicking 'Add Task', a new row is automatically added to the table (this part has been completed) and the input field within ...

I am interested in generating a Stacked Chart in Google Charts using data from a JSON file

Hey there, I'm looking to generate a stacked chart using JSON data in Google Charts. My current challenge revolves around the code snippet var data = google.visualization.arrayToDataTable([. <?php $tmp = array(); require "configdashboard.php"; /* ...

Trouble with updating the view when an array is modified in ng-repeat? It seems like using $scope.$apply() may not

When updating the array inside a function, the view does not automatically update. However, if you use console.log to check the array after pushing values, it shows the updated array. Even trying $scope.apply() inside $timeout did not solve this issue. Ja ...

Exploring ways to query a MySQL JSON column for multiple conditions within the same array index

My current setup involves MYSql server version 8.0.17. I need to retrieve records where the uId= 'UR000001' and VIEW = 'Y' from the security column in the table. Viewid Security VW0000000002 {"security": [{"uId": "UR000001 ...

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

Struggle with incorporating a file

As part of the login process, I have two options available: easy login and standard login. The easy login requires an employee ID, birthdate, and captcha answer, while the standard login asks for first name, last name, birthdate, and captcha. To facilitate ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

Generating a JSON object through the comparison of two other JSON objects

I need to create a new JSON object called selectedProductAttributes, which is generated by comparing the contents of a second JSON object (selectedProductAttributesNames) with a third object (allProductAttributes). Let me provide some examples to make this ...

What is the best way to retrieve classes from arrays and apply styling to them using javascript?

Imagine having 3 unique classes: alpha, beta, and gamma. Each class contains 3 individual div elements like so: <div class="alpha"></div> <div class="alpha"></div> <div class="alpha"></div> <div class="beta">< ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...