Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so:

<div v-html="htmlText"></div>
I have written code to highlight text and it works on regular text:

Vue.filter('highlight', function (word, query) {
  if (query !== '') {
    let check = new RegExp(query, "ig");
    return word.toString().replace(check, function (matchedText, a, b) {
      return ('<strong class="mark">' + matchedText + '</strong>');
    });
  } else {
    return word;
}
<div v-html="$options.filters.highlight(htmlText, myWord)">
</div>

I am trying to highlight a specific word within this text without affecting the HTML tags. Can someone please assist? Thank you.

Answer №1

If you're open to using external libraries, one option is mark.js.

With mark.js, you can easily highlight text using regular expressions and apply it across HTML elements. Below is a Vue example demonstrating how mark.js can be integrated:

var demo = new Vue({
  el: '#demo',
  data: {
    // The html content to be highlighted
    html: '<div>Hello <span>this </span>is <span>some </span>text</div>',
    
    // The html content with highlighting applied
    highlightedHtml: '',
    
    // The search term for highlighting
    search: 'Hello'
  },
  watch: {
    // When the search term changes: recompute the marked html content
    'search': {
      handler: function() {
        // Create an element with the given html content and assign a unique id 
        // for potential removal in the future
        let id =  'id' + (new Date()).getTime();
        $('body').append(`<div id="${id}" style="display:none">${this.html}</div>`);
        
        // Instantiate a Mark instance on the newly created element
        let markInstance = new Mark('#' + id);
        
        // Mark the text with the specified search string. Upon completion,
        // update the highlighted text and remove the temporary element
        markInstance.markRegExp(new RegExp(this.search, 'gmi'), {
          done: () => {
            this.highlightedHtml = $('#' + id)[0].innerHTML;
            $('#' + id).remove();
          },
          acrossElements: true,
        });
    },
      immediate: true
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.0/mark.js"></script>

<div id="demo">
  <div>/ <input type="text" v-model="search"> /gmi</div>
  <div v-html="highlightedHtml"></div>
</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

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

Utilizing dual identifiers in a Jquery plugin

I am currently working with a jQuery plugin and I need to apply the same functionality to two different IDs. How can I achieve this? It involves a next and previous functionality where clicking on the next button automatically scrolls both divs. The issu ...

Error 404: This page seems to have gone missing. Django and react-router

Struggling to integrate reactjs and react-router (1.x) with my Django project. I'm finding it challenging to make everything work together seamlessly. For more details, you can check out the project on GitHub: https://github.com/liondancer/django-che ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

What is the best way to incorporate a search bar into a dropdown menu?

Would someone be able to assist me in adding a search bar as the primary value of the dropdown menu? I am using ASP.NET MVC and this is my current code snippet. <div class="col-md-8"> <div class="dropdown"> <div class="chzn-d ...

Is it possible to organize MongoDB records that possess identical update timestamps?

My goal is to validate a route within my Express server using Supertest. This particular route retrieves data from a MongoDB, and the data is then sorted based on the updatedAt field. While attempting to test the order of the output, I encountered an issu ...

What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, whic ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

Exploring the application of the PUT method specific to a card ID in vue.js

A dashboard on my interface showcases various cards containing data retrieved from the backend API and stored in an array called notes[]. When I click on a specific card, a pop-up named updatecard should appear based on its id. However, I am facing issues ...

Keeping extensive files/information on disk in order to alleviate browser memory usage in JavaScript

Currently, I am faced with a challenge involving the encryption of very large files. Unfortunately, my browser keeps crashing due to running out of memory while trying to handle these massive files. To address this issue, I am considering transferring som ...

Task that merges multiple JSON files into one using Gulp

Within my directory, I have a collection of JSON files that contain arrays of objects. Folder A file1.json file2.json file3.json All the files in this folder have the same structure (a single array containing multiple objects). My goal is to execu ...

Hidden warning to React-select for being uncontrolled

I've integrated react-select into my code: import React, {Component} from 'react'; import Select, {createFilter} from 'react-select'; let _ = require('underscore') class Test extends Component { constructor(props) ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

How can I create a JSON string that exactly matches the data source needed for a pie chart? Any tips

received JSON string: "{Date:'15/05/2015',y:'6'}, {Date:'01/08/2015',y:'6'}, {Date:'02/08/2015',y:'6'}, {Date:'08/08/2015',y:'72'}, {Date:'09/08/2015',y:&apo ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...

"Exploring the power of Node.js Virtual Machines and the magic of

I'm currently facing a challenge with reading and extracting data from a dynamically generated HTML file that contains a commented out JavaScript object. My goal is to retrieve this object as a string and execute it using VM's runInNewContext(). ...

Forward incoming requests to a distinct backend server using vue-cli

I have chosen the vue-cli webpack-simple template for creating my projects, and I am looking to set up proxy requests to a different backend server. What is the simplest way to accomplish this? ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...