Mark.js + Vue

Highlighting text using Mark.js and Vue

by asemahle

HTML

<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>

JavaScript

var demo = new Vue({
  el: '#demo',
  data: {
    // The html to highlight
    html: '<div>Hello <span>this </span>is <span>some </span>text</div>',
    
    // The html with highlighting
    highlightedHtml: '',
    
    // The search term to highlight
    search: 'Hello'
  },
  watch: {
    // When the search term changes: recalculate the highlighted html
    'search': {
      handler: function() {
      	// We create an element with the html to mark. Give it a unique id 
        // so it can be removed later
        let id =  'id' + (new Date()).getTime();
        $('body').append(`<div id="${id}" style="hidden">${this.html}</div>`);
        
        // Create a Mark instance on the new element
        let markInstance = new Mark('#' + id);
        
        // Mark the text with the search string. When the operation is complete,
        // update the hightlighted 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
    }
  }
});