Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result.

highlightRepeatedText(str) {
  // Split the string into an array of sentences
  const sentencesArray = str.split(".");
  // Initialize an empty array to store repeated sentences
  let repeatedSentences = [];

  // Iterate over the array of sentences
  for (let i = 0; i < sentencesArray.length; i++) {
    const currentSentence = sentencesArray[i].trim();
    // Check if current sentence is already in repeated array, if yes then highlight it
    if (repeatedSentences.includes(currentSentence)) {
      sentencesArray[i] = `<mark>${currentSentence}</mark>`;
    } else {
      // If not, add it to the repeated array
      repeatedSentences.push(currentSentence);
    }
  }

  // Return the modified string with highlighted repeated sentences
  return sentencesArray.join(".");
},

Answer №1

If you are looking for a solution that involves using v-html or understanding how a function is called, the code snippet provided below might be helpful:

<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>

Check out the playground link for more details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

What is the reason for not allowing return statements in the ternary operator?

Imagine you have a basic form and you want to determine if the form has been modified. If it has changed, you want to submit it; otherwise, you want to prevent form submission. To tackle this, instead of using an if-else statement, I decided to go for a te ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Is there a way for me to retrieve the value from an input, round it up to the nearest even number, and assign it to a new variable?

I am working on a project that involves two text boxes and a drop-down menu for providing rates. The values in the text boxes are given as inches. I want these inputs to be taken as values, rounded up to the next even number, and then set as variables. How ...

Expandable full-width JavaScript accordion for seamless navigation

Currently, I am working on a simple on-page JavaScript application that consists of multiple data pages within one main page. My goal is to create a horizontal accordion effect where clicking on headers on either side will smoothly switch between the diffe ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

Intercepting and handling errors thrown by a Node module

I have been encountering an issue with a module that throws errors without them being returned as part of the callback, causing the program to stop when an error is thrown. The code snippet I am using looks like this: co(function*(){ try{ for (let ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

How come my total isn't zero after I get a 1 on the dice roll?

I've been working on a dice game where if either of the dice rolls a 1, the score is set to 1. However, I'm having trouble getting that part of my code to work properly. I'm confident that everything else is functioning correctly. v ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...

Guide on utilizing Subscribe Observable for performing lookup in Angular

I am new to Angular and seeking guidance as my approach may not be the best. Please advise me on a better solution if you have one. My goal is to display a list of records in table format, retrieved from the database where only Foreign Keys IDs are availa ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Data has been successfully acquired through the query, however, it cannot be accessed via the GraphQL API

After successfully building the API with Apollo Server and verifying its functionality in GraphiQL, I proceeded to make requests to the API from a front-end React app using Apollo Client. const [getUserPosts, { loading, error, data }] = useLazyQuery(GET_US ...

"Troubleshooting: Why is the JavaScript canvas.toDataURL method returning an

While I know this question has been asked multiple times before, I still haven't been able to find a solution. My goal is to take an image, rotate it, and place it in an HTML canvas. To achieve this, I am utilizing another canvas where I rotate the i ...

Discover the method of extracting parameters from an event in Vuetify Vue.js

I am currently delving into the world of Vuetify and Vue.js, and I have a question regarding retrieving parameters when clicking on my treeview: For example, in the Chrome console with the Vue extension installed, I see: vue event update:active This pro ...

uib-datepicker-popup allowing for changing minimum mode dynamically

Is there a way to dynamically set the minMode of an Angular Bootstrap Datepicker? I managed to achieve this using the following code: <input type="text" ng-model="myDate" uib-datepicker-popup="{{datepickerFormat}}" datepicker-options="{& ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

Stopping $interval using promise after a specific condition is satisfied using Angular timer

I'm struggling to figure out why my $interval service isn't canceling properly. It seems like something important is missing. In my code, I've set up a counter that's tied to a counting property: $scope.sessionCounter $scope.sessionC ...