N
N
Nstk542020-11-16 17:06:16
Vue.js
Nstk54, 2020-11-16 17:06:16

How to select a part of the text?

There is a list of posts, the user can search through them. The task is to highlight the part of the text that the user was looking for.

When you try to replace Примерwith, <span>Пример</span>it gives text on the page <span>Пример</span>instead of the element span.

How to make vue render a new tag? I don’t want to climb through this.$el, but so far I have no other options.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-11-16
@Nstk54

computed: {
  highlightedText() {
    const { text, search } = this;
    return search
      ? text.split(RegExp(`(${search.replace(/[\\^$|.*?+{}()[\]]/g, '\\$&')})`, 'gi'))
      : [ text ];
  },
},

<template v-for="(n, i) in highlightedText">
  <mark v-if="i % 2">{{ n }}</mark>
  <template v-else>{{ n }}</template>
</template>

https://jsfiddle.net/0Lf6a5x9/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question