Filtering text for highlighting in Vue.js is a breeze

Struggling to create a text highlight filter using vuejs. The task involves iterating through an array of words, highlighting any matches with a span and class. However, I'm facing difficulty in getting the data to return with proper HTML formatting in vuejs. Any suggestions or solutions would be greatly appreciated as I am currently at an impasse.

Vue.filter('highlight', function(words, query){
    // Iterate through **words**, apply span style to matches in **query**
   // Return formatted string to display on HTML page
})

Answer №1

Vuejs2.X has phased out HTML interpolations {{{ foo }}} in favor of the v-html directive. Starting from version 2.x, Vue.js now supports raw JavaScript templating (similar to React) alongside HTML templating.
@jeff's response is accurate for Vuejs 1.x versions. However, if you encountered issues with {{{}}} or want to interpret tags within HTML, use v-html. This instructs Vue to evaluate the string as HTML:

<span v-html="$options.filters.highlight(item, val)">{{ item }}</span>

highlight filter:

Vue.filter('highlight', function(word, query){
  var check = new RegExp(query, "ig");
  return word.toString().replace(check, function(matchedText,a,b){
      return ('<strong>' + matchedText + '</strong>');
  });
});

Alternatively, you can utilize @Thomas Ferro's filter

Answer №2

Just like Jeff mentioned, the basic mustaches interpret the data as plain text.

If you want to add your own span, you can do so by using the String.replace() method.

For example, check out this basic demo: https://jsfiddle.net/0jew7LLz/

Vue.filter('highlight', function(sentence, word) {
    return sentence.replace(word, '<span class="highlight">' + word + '</span>');
});

Answer №3

The concept involves using the split method and retaining the words that match the specified regular expression.

Here's a user-friendly component in Vue.js that sanitizes HTML and highlights a regex pattern searching for multiple words:

Vue.component('child', {
  props: ['msg', 'search', 'effect'],
  template: '<span><span v-for="(s, i) in parsedMsg" v-bind:class="getClass(i%2)">{{s}}</span></span>',
  methods: {
    getClass: function(i) {
      var myClass = {};
      myClass[this.effect] = !!i;
      return myClass;
    },
  },
  computed: {
    parsedSearch : function () {
        return '(' + this.search.trim().replace(/ +/g, '|') + ')';
    },
    parsedMsg: function() {
        return this.msg.split(
        new RegExp(this.parsedSearch , 'gi'));
    }
  }
})

new Vue({
  el: '#app',
  }
  // ...
})

Example of usage:

<div id="app">
  <child msg="My life so good and awesome, is'nt it great?" search="   life   is   good  " effect='highlight'> </child>
</div>

View on jsfiddle:

https://jsfiddle.net/50xvqatm/

Answer №4

Make sure to employ {{{ bar | emphasize }}} using 3 brackets, as opposed to 2 {{}}. Using two brackets will result in HTML escaping.

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

Experiencing difficulties accessing the API route through Express

Every time I attempt to access /api/file, I am receiving a status code of 404. Here is the relevant code snippet: app.js : ... app.use("/api", require("./routes/users")); app.use("/api", require("./routes/file")); ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

What is the best way to dynamically retrieve a URL and utilize it as a hyperlink using jQuery?

Is there a way to retrieve the current URL and use it as a link in jQuery? For example, if my browser is currently on page mysite.com/index.php?page=post&see=11, I would like to use this URL in my link and append /new/ after the domain name, like so: ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

The function `collect` cannot be found for the object #<Page:0x007f4f200a9350

Seeking assistance with an error I've encountered. As a novice, I'm still navigating my way through this, so any guidance on how to resolve it would be greatly appreciated. Attached is the portion of code that is triggering the error: 3: <%= ...

Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, ...

What is the best way to implement a loop using JQuery?

<script> $(function() { $('.slideshow').each(function(index, element) { $(element).crossSlide({ sleep: 2, fade: 1 }, [ { src: 'picture' + (index + 1) + '.jpg' } ]); }); ...

Show various columns in Select2

I am currently utilizing select2 and I am interested in displaying a multicolumn table as a dropdown. In order to achieve this, the width of the drop-down container should differ (be larger) than the input itself. Is it feasible to accomplish this? Furth ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

I am currently working on implementing a feature in my app that allows users to easily log in using their Google account

Currently, I am in the process of enhancing my app to enable users to log in using their Google account. The frontend is built with ReactJS, tailwindcss, and sanity. The login button successfully writes user data to the sanity database. However, I suspect ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...

Encountering ReferenceError while running production build with Webpack

After upgrading to webpack 3.10.0 and Babel 6.26, I managed to fix my dev build but encountered issues with the prod build that I can't seem to resolve. This is the error message I am seeing: ERROR in ./src/index.js Module build failed: ReferenceErr ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...

Establishing the primary meta properties on Vue Router

I've checked out the documentation here, and it appears that the meta property on the VueRouter object doesn't seem to have any effect (no description provided in the documentation)... Let's consider the following routes: let routes = [ ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...