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

Visual Studio Terminal displaying "Module Not Found" error message

After successfully downloading nodejs onto my computer, I created a javascript file and stored it in a folder on my desktop. However, when I tried to run the JS code using the Visual Studio terminal, I encountered the following error message. I am confiden ...

Angular directive that verifies the presence of a specific number of child li elements

Currently, I have a basic ul that utilizes ng-repeats to display li elements fetched from an external source via a promise. There is also a search input present which filters these elements, and I want the ul to be hidden when there are no more elements th ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Encountered error code 422 Unprocessable_entity upon submitting form to Rails API via Vue.js application

Currently, I am in the process of developing an application using Rails 6 Api as a backend and Vue as a standalone web app. After successfully setting up my sign-up form, I encountered a frustrating issue upon submission where I received a Completed 422 U ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

How can Vue.js update the displayed information when the selection option changes?

Ensuring the total weight of the products remains accurate when changing the unit of measurement is essential. Currently, although the data in the array is being updated, these changes are only reflected on the screen after clicking on other input fields. ...

I am looking to implement an animation that automatically scrolls to the bottom of a scrollable DIV when the page is loaded

My DIV is configured with overflow-y set to scroll. .scrolling-div { width: 85%; height: 200px; overflow-y: scroll; } If I have an abundance of content within this div, my goal is for it to automatically scroll to the bottom upon loading the page. I am ...

A guide to implementing X-Frame-Options in an express.js web application using node.js

My dilemma involves serving static assets within iframes across various desktop and mobile web clients. Specifically, I am seeking guidance on how to whitelist a select group of origins for allowing the setting of X-Frame-Options headers. This will enable ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Is this included in the total number of reads?

Following my query with CollectionsGroup, I attempted to retrieve the information of the parent's parent like this: db.collectionGroup('teams').where('players', 'array-contains', currentUser.uid).get().then(function(snaps ...

Dragging a div element within a table

I am working on an HTML code where I need to make the colored divs draggable and fit them into specific table cells. The green div should occupy 2 cell spaces, light blue 3 cell spaces, yellow 4 cell spaces, and dark blue 5 cell spaces. While I have the d ...

Create your masterpiece on a rotated canvas

My goal is to draw on a canvas using the mouse, even after rotating and scaling the canvas container. The issue I am facing is that the mouse coordinates get affected by the rotation and scaling, making it difficult to draw correctly. I have tried switch ...

Using the onclick event with an image created through PHP code

I am currently in the process of developing a dynamic image represented as a graph displaying the number of documents generated each day. This interactive image is being created using PHP, and I aim to improve user engagement by enabling them to click on t ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...

Can images be sent to an Express API using SvelteKit's `on:change` event handler in combination with Form Actions?

I have a SvelteKit application that interacts with an Express API to store user data. Within my app, there is a form containing an input file field where users can upload images to be saved on the Express server using Form Actions. The issue I am facing ...

Navigating with React Router using server-side routing in the web browser

I'm currently developing a web application that utilizes react on the client side and express on the server side. For routing the client pages, I've been using react-router (link). Initially, I had success using hashHistory, but now I want to ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

I am looking to transfer an image stored in a database onto a card

One issue I am facing is that when trying to display an image from a database, uploaded by a user and showing on a card with additional information like name and price, an icon resembling a paper with green appears in the output. Here's my code snippe ...

What is the proper way to access the current value of a computed property from within its own computation method?

Our goal is to activate a query when a string reaches a length of 3 characters or more, and keep it activated once triggered. Leveraging the Vue 2 Composition API, we have implemented a reactive object to manage the status of queries: import { computed, de ...

What is the significance of having 8 pending specs in E2E Protractor tests on Firefox?

Each time I execute my tests, the following results are displayed: There were 11 specs tested with 0 failures and there are 8 pending specs. The test execution took 56.861 seconds to complete. [launcher] There are no instances of WebDriver still running ...