H
H
Horus1232020-12-01 15:31:23
Vue.js
Horus123, 2020-12-01 15:31:23

How to highlight text in html?

How to highlight text between html tags? I have a finished article in the form of html, it is necessary to highlight the relevant words when searching.

If the text is not framed by html tags, then everything is fine. But how to implement selection in such text, for example:

<p><b>Хабр</b> помоги найти ответ на вопрос</p>

Here is what is now:
Vue.js

search= ""

 let words = el.text.split(' ')
        for (let key in words) {
          if (words[key].includes(this.search)) {
            words[key] = "<mark>" + words[key] + "</mark>";
          }
        }
        el.text = n.join(" ");


I can't write the split method correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-01
@Horus123

methods: {
  marked: (text, search) => search
    ? text.replace(RegExp(search.replace(/[\\^$|.*?+{}()[\]]/g, '\\$&'), 'gi'), '<mark>$&</mark>')
    : text,
},

<div v-html="marked(text, search)"></div>
If the selection needs to cross tag boundaries, then you should take some ready-made library for this matter, such as, say, mark.js ( an example of using it with vue ).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question