Exploring Vue.js: Navigating through highlighted search terms with previous and next buttons

Is there a way to allow users to navigate through highlighted search results using 'next / previous' arrows? Something similar to the feature in Google Docs shown below:

https://i.sstatic.net/44LpL.png

I already have the code to highlight all occurrences using a filter and regular expression :

<p v-html="$options.filters.highlightSearchResults(theText,  searchTerms)"></p>

And here's the code snippet:

filters: {
  highlightSearchResults(theText, searchTerms) {
    const re = new RegExp(searchTerms, "gi")
    return theText.replace(re, (match) => `<span style="background-color:#ffff00">${match}</span>`
  }

However, I'm stuck on how to implement the navigation functionality for cycling through the found instances. Any guidance would be greatly appreciated.

Answer №1

To improve the functionality, you can establish a variable called currentIndex that points to the index of the currently highlighted item (and is modified by the Next/Prev buttons).

export default {
  data() {
    currentIndex: 0,
  }
}

Additionally, maintain an iterator index in your string replacer method that will only wrap the matching text with a highlighting <span> when it matches the currentIndex:

export default {
  methods: {
    highlightSearchResults(theText, searchTerms) {
      const re = new RegExp(searchTerms, 'gi')
      let i = 0
      return theText.replace(re, (match) =>
        (i++ == this.currentIndex)
                             ? `<span style="background-color:#ffff00">${match}</span>`
                             : match
      )
    },
  }
}

Check out the demo here.

To optimize rendering performance, consider replacing the highlightSearchResults function in the template with a computed property, as the value would be cached and reused in the subsequent render:

<template>
  <p v-html="highlightedText"></p>
</template>

<script>
export default {
  computed: {
    highlightedText() {
      return this.highlightSearchResults(this.theText, this.searchTerms)
    }
  }
}
</script>

See the optimized version in action.

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

locate handlers for events using selenium web automation

Recently, I began exploring Selenium. Can Selenium locate event handlers connected to an HTML element? These handlers, such as onclick for a button, may be dynamically added using addEventListener. ...

The message that keeps popping up says "TypeError: Unable to access the 'execute' property of an undefined object."

I am currently working on creating a Discord bot and encountering an error that says "TypeError: Cannot read property 'execute' undefined". Despite trying multiple solutions, I am still facing some issues with my code. Any help in solving this pr ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

"Is there a way to retrieve the file size from a source on a different site

Hey everyone, I'm pulling src's from another website and have them in an array like ["www.another.com/pic1.png", "www.another2.com/pic2.jpg"]. I tried using XMLHttpRequest and checking the file.size, but CORS restrictions are preventing me from ...

What is the process for activating and deactivating the scroll trigger within Material UI's useScrollTrigger module?

I'm currently working on setting up a survey page with Material UI in React. My goal is to have the survey questions appear when the user scrolls over them and disappear when they scroll out of view, similar to the behavior on this page. After some r ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Encountering an error with NodeJs, AngularJs, and Mongoose: TypeError - Object.keys invoked on a non-object leading to Function.keys (native)

Here is the code snippet related to the issue: server.js file: app.post('/user', function(req,res){ console.log(req.body); var user = mongoose.Schema('User',req.body); user.save(function(err,user){ if(err) console.l ...

Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side. https://i.stack.i ...

What steps do I need to take to integrate FontAwesome with the vue-cli webpack-simple template?

First, I create a new project using vue-cli: vue init webpack-simple grid-prototype Next, I add FontAwesome to my project via npm: npm install --save fontawesome Once installed, I include it in my main.js file with the following code: import 'fon ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Unacceptable response from AJAX function

My goal is to extract specific information from this ajax function, such as the thumbnail image and the owner of the image. It seems like the function is not recognizing data.images[i].imgurl and data.images[i].username. AJAX call in ajax.php require_o ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

Animation event in CSS3 fails to trigger on Firefox browser

Exploring the potential of CSS3 animation to detect when an input transitions from the enable to disable state, I encountered a challenge specifically in Firefox. Here is the code snippet that showcases the issue: View Demo on jsFiddle HTML: <input t ...

The XMLHttpRequest is displaying additional characters within its response

Upon completing an XMLHttpRequest(), I am receiving the unexpected output of "true↵↵↵". In my php file, all I have is echo json_encode(true); Can anyone shed some light on why this strange behavior is occurring? Thank you ...

Tips for effectively passing parameters in nested controllers within AngularJS

Currently, I am facing a scenario where I retrieve data from a REST API in a controller, display that data using ng-repeat, then have to execute another controller within that loop. This involves passing data from the initial controller, performing some op ...

Achieve a stunning visual effect by gradually blending the background image in a parallax

Adding some parallax scrolling background images to my site using this awesome plugin: Looking to achieve a fade out effect on user scroll, similar to what is seen on this cool website: Tried implementing the code below but it doesn't seem to work d ...

Managing several drop elements using class dynamically

I am facing a challenge in combining drag and drop listeners into one function to create dynamic zones with the same class. This will allow me to call a single function for uploading files. The upload function is currently working correctly, but I need a ...

Stuck at loading: Electron encountering issues with Aurelia Navigation Setup

UPDATE 1: An unexpected challenge has arisen As I endeavored to install and configure Aurelia Navigation with Typescript and Electron by following these instructions: https://github.com/aurelia/skeleton-navigation/tree/master/skeleton-typescript I succe ...