简体   繁体   中英

how to highlight a word inside html tags without highlighting tags in vue

i have a tag with v-html that renders a html text and shows it,like this:

 <div v-html="htmlText"></div> 
i write this code for highlighting text and it works on normal 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 want to highlight a word inside this text without highlighting html tags. please help. thanks.

If you're not opposed to external dependencies, you could use mark.js .

It allows for highlighting text using a RegExp, and can work across HTML tags. Here is an example of how it might be used with Vue:

 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 } } }); 
 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM