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

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

Exploring the Power of GraphQL Args in Mutation Operations

Currently, I am in the process of developing a blog service using express and apollo-express in conjunction with mongodb (mongoose). While implementing mutation queries, I have encountered difficulties in accessing the arguments of a mutation query. I am ...

Trouble displaying custom markers in VueJS using Google Maps API

I have integrated vue2-google-maps to display a map and add markers on specific locations. Here is the code snippet showing the map components along with the props passed to it. <gmap-map id="map" :center="center" :zoom="5" ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

What is the best way to make the first <p> tags bold within an array?

I tried using ::first-line, but it bolds all the p tags in the array. What I want is to only bold the first p tag which contains "Hello". <div v-for="item in first" :key="item.id"> <p class="cat_name" >{{ ...

How can I delete the onmouseover function in HTML?

Is there a way to remove the (onmouseover="mouseoversound.playclip()") function from the following HTML code? <a href="roster.html" onmouseover="mouseoversound.playclip()">Roster</a> Can we instead implement this functionality in a JavaScript ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

Angular parent scope does not reflect changes when a directive updates the shared scope variable

My directive is designed to validate and modify a specific binded value before triggering the button action. However, I am facing an issue where any updates made to the directive value are not being reflected in the parent scope. Even though I have used (= ...

An efficient method for removing a column using JavaScript

Hello, I'm seeking assistance with the following code snippet: $(document).on('click', 'button[id=delete_column]', function () { if (col_number > 1) { $('#column' + col_number).remove(); $('#col ...

Easily send maps and directions straight to your mobile device with mapQuest

Currently creating a web application with mapQuest integration. I have two queries: 1) Is there a way to share routes from the web app to my phone? 2) How can I track my phone device and display the route on the web app? Appreciate any assistance. PS: Us ...

Code that achieves the same functionality but does not rely on the

I utilized a tutorial to obtain the ajax code below. The tutorial referenced the library jquery.form.js. Here is the code snippet provided: function onsuccess(response,status){ $("#onsuccessmsg").html(response); alert(response); } $("# ...

When triggered, the onClick event will launch multiple Material-UI dialogs simultaneously

I'm working on creating a user-friendly employee directory using Material-UI's dialog modals. However, I'm facing an issue where clicking on any employee card opens all dialog boxes instead of just the one related to that specific employee. ...

Implementing a time to live feature in socket.io can be accomplished by setting a

After extensive searching online, I haven't been able to find any resources on how to implement the 'time-to-live' function using Socket.io. In my project, I am utilizing Node.js with express. The functionality of the mentioned time-to-live ...

Faking a distant site to access a nearby document

I am currently developing a Vue JS front-end that communicates with a C# webapi application. The webapi is designed to store images in a folder located on the E: drive of the server and provide src links for the UI to use. While everything works as expect ...

Dealing with a syntax error in JavaScript (Codecademy)

I have been working my way through the JavaScript course on Codeacademy and for the most part, I've been able to figure things out on my own. However, I've hit a roadblock with my code and can't seem to get it right. Here is the code I&apos ...

Enhance Odoo Conversations (mail)

I've been attempting to customize the Odoo discussions, but have hit a roadblock. Here is my goal: I am adding messages using the "New Message" button to an Odoo module (in class mro.order). The messages are appearing in the Discussions module: How ...

Challenge with timing in slideUp and slideDown animations (jQuery)

The element with the class "heady" is designed to slide up when the document height percentage is below 25%. If you scroll back up, it should reappear after a delay of 1400ms. The problem arises when this action needs to repeat, as the class does not sli ...

Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following th ...

Is it possible to impose a different style on an element from another culture?

I am currently developing a themes library along with a demo page. The challenge I'm facing is that the demo page needs to showcase styles from the library without using all of the elements. For instance, consider the following style in an external s ...