Saikat Sen
Saikat Sen

Reputation: 1

Problem while highlighting repeated sentence in vue js

I want to mark some repeated sentences from a text area input paragraph. I tried the below code but it's not working.

highlightRepeated(str) {
  // Split the string into an array of sentences
  const sentences = str.split(".");
  // Create a variable to store the repeated sentences
  let repeated = [];

  // Iterate over the array of sentences
  for (let i = 0; i < sentences.length; i++) {
    const sentence = sentences[i].trim();
    // If the sentence has already been added to the repeated array, highlight it
    if (repeated.includes(sentence)) {
      sentences[i] = `<mark>${sentence}</mark>`;
    } else {
      // Otherwise, add it to the repeated array
      repeated.push(sentence);
    }
  }

  // Return the modified string
  return sentences.join(".");
},

Upvotes: 0

Views: 42

Answers (1)

AnandShiva
AnandShiva

Reputation: 1349

The following snippet works for me. See if you want to use v-html. Or how the function is being called.

<script>
import { ref } from 'vue'

export default {
  data(){
    return {
      msg: 'Hello'
    }
  },
    computed: {
    highlightedText(){
      const hlt = this.highlightRepeated(this.msg);
      console.log(hlt);
      return hlt;
    }
  },
  methods:{
    highlightRepeated(str) {
      // Split the string into an array of sentences
      const sentences = str.split(".");
      // Create a variable to store the repeated sentences
      let repeated = [];

      // Iterate over the array of sentences
      for (let i = 0; i < sentences.length; i++) {
        const sentence = sentences[i].trim();
        // If the sentence has already been added to the repeated array, highlight it
        if (repeated.includes(sentence)) {
          sentences[i] = `<mark>${sentence}</mark>`;
        } else {
          // Otherwise, add it to the repeated array
          repeated.push(sentence);
        }
      }
      // Return the modified string
      return sentences.join(".");
    }
  }
}
</script>

<template>
  <h1>{{ msg }}</h1>
    <h1 v-html="highlightedText"></h1>

  <input v-model="msg">
</template>

playground link

Upvotes: 2

Related Questions