[Vuejs]-Vue.js 2: Highlight string occurrence

2👍

The only problem with my solution is, that the whole v-html-text is now lowercase..
I defined the highlight-method in the methods-block:

methods: {
    highlight(words, query) {
        if(query === '') { return words }
        if(typeof(words) === 'number') {
            words = '' + words + ''
        }
        // when removing the .toLowerCase() your search becomes case-sensitive
        return words.toLowerCase().replace(query, '<span style="background: yellow;">' + query + '</span>')
    }
}

In my template it looks like this:

<span v-html="highlight('This is some sort of test', 'some')"> // should now highlight 'some'
👤Kodiak

1👍

There are filters in vuejs2 as well. You just create your own method to highlight.

<div>{{ 'some-text' | highlight }}    

new Vue({
  // ...
  filters: {
    highlight: function (value) {
      // logic
    }
  }
})

Leave a comment