Spotting repeated terms within an HTML document

I have a table with results generated using v-html (meaning the text inside the table does not appear until the page is rendered). I want to compare two rows and highlight any duplicate words they may contain.

While looking for examples, I came across a project that showcased what I need, although it was more complex than necessary. This question on Stack Overflow resembles mine, but it requires defining the words rather than letting the page identify them automatically.

For instance, here's an illustration of the desired output:

<table>
  <tr>
    <td v-html="link.orderdesciption">
    order:<br />
   <mark> TV </mark><br /> <!--note that the contents of the td would not appear in markup due to being v-html-->
    PS3 <br />
    Laptop
    </td>
    <td>
    qty:<br />
    1<br />
    2<br />
    1<br />
    </td>
  </tr>
  <tr>
    <td>
    ----------------
    </td>
    <td>
    ----------------
    </td>
  </tr>
  <tr>
    <td v-html="link.orderrecieved">
    recieved:<br /> <!--same note as above, v-html only shows-->
    <mark> TV </mark><br />
    Desktop<br />
    </td>
  </tr>
</table>

I've been attempting to work on this issue, but I'm unsure about the next steps:

var text = $('td').text(),
    words = text.split(' '),
    sortedWords = words.slice(0).sort(),
    duplicateWords = [];


for (var i=0; i<sortedWords.length-1; i++) {
    if (sortedWords[i+1] == sortedWords[i]) {
        duplicateWords.push(sortedWords[i]);
    }
}
duplicateWords = $.unique(duplicateWords);

Any advice or guidance would be greatly appreciated,

Answer №1

To find the duplicate words, utilize the reduce method, then loop through the tds to check if the text is included in the duplicate words Array. If it is, enclose the text within mark tags.

const tds = document.querySelectorAll('td');

const groupByOccurence = [...tds].reduce((accu, td) => {
  const textArr = td.innerHTML.split('<br>').map((word) => word.trim()).filter((word) => word.length > 0 && word.match(/[a-zA-Z]+/g));
  textArr.forEach((text) => {
    accu[text] = (accu[text] || 0) + 1;
  });
  return accu;
}, {});

const duplicateWords = Object.entries(groupByOccurence).filter(([_, val]) => val > 1).map(([key, _]) => key);

tds.forEach((td) => {
  const textArr = td.innerHTML.split('<br>').map((word) => word.trim());
  let str = "";
  textArr.forEach((text) => {
    if (duplicateWords.includes(text)) {
      str += '<mark>' + text + '</mark><br>';
    } else {
      str += text + '<br>';
    }
    td.innerHTML = str;
  })
});

const trs = document.querySelectorAll('tr');

trs.forEach((tr, i) => {
  const specialChartds = [...tr.querySelectorAll('td')].filter((td) => !td.textContent.match(/[a-zA-Z]+/g));
  if (!specialChartds) {
    tr.append(tds[i]);
  }
});
<table>
  <tr>
    <td>
      order:<br /> TV
      <br /> PS3 <br /> Laptop
    </td>
    <td>
      qty:<br /> 1
      <br /> 2
      <br /> 1
      <br />
    </td>
  </tr>
  <tr>
    <td>
      ----------------
    </td>
    <td>
      ----------------
    </td>
  </tr>
  <tr>
    <td>
      recieved:<br /> TV <br /> Desktop
      <br />
    </td>
  </tr>
</table>

Answer №2

To achieve the desired outcome, follow the instructions below:

  1. Iterate through each table element to retrieve all words
  2. Create an array with duplicate words from the previous step using the filter method
  3. Loop through all table cells and mark duplicate words with a tag

var text = $('table');
var arr = [];

//Step 1: Getting All words from table
var words = text.each(function(){
   let val = $(this).text().replace(/\n|\r/g,' ').split(' ').filter(Boolean);
   arr.push(...val)
})


//Step 2: Finding duplicate words
let duplicate = arr.filter(function(value,index,self){ return (self.indexOf(value) !== index && isNaN(parseInt(value)) && value.match(/[A-Za-z]/) !== null)})


//Step 3: Marking duplicate words in each row
$('td').each(function(){
   let val = $(this).text();
   let openMark = '<mark>'
   let closeMark = '</mark>'
   duplicate.forEach(v => {
      if(val.indexOf(v) !== -1){
          var html = $(this).html().replace(v, openMark + v + closeMark)
          $(this).html(html)
      }
   })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
    order:<br />
   TV<br />
    PS3 <br />
    Laptop
    </td>
    <td>
    qty:<br />
    1<br />
    2<br />
    1<br />
    </td>
  </tr>
  <tr>
    <td>
    ----------------
    </td>
    <td>
    ----------------
    </td>
  </tr>
  <tr>
    <td>
    received:<br />
    TV<br />
    Desktop<br />
    </td>
  </tr>
</table>

Check out the code in action on CodePen: here

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

Attempting to utilize Ajax to save a file in Laravel, however unsure of what may be causing the issue in my code

Looking for a way to save an image file using ajax in Laravel, here is the code I am currently using: Controller public function store(Request $request) { $item = new Item; // if remove $it_files_path , $it_files_name , $path code work co ...

Retrieve the HTML element by providing its specific index within the DOM structure of the document

I am working with the HTML source of a document stored as a string and have the index i which indicates where an element starts within this string. I am looking to create a function called getElementByIndex(i) that will return the appropriate JavaScript D ...

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Access a three.js scene from a canvas element within the local environment to make alterations

Is it necessary to keep Three.js variables (scene, camera, renderer etc.) globally? I have devised a function that initializes canvas elements by taking a DOM position and other information to build the scene. This function is then passed to a render func ...

Uncovering Modified Form Elements Using jQuery

I am managing a form with the ID "search_options" and tracking changes in the form using the following code: $("#search_options").change(function() { // Bla Bla Bla }); Within this form, I have various inputs including one with the ID "p ...

Achieving full-screen fill with inline SVG

I recently purchased an svg graphic and exported it to a .svg file with the intention of using it in inline HTML. I placed it within the <body> tag of my document, but now I'm trying to make it fill the entire width and height of the screen. I&a ...

Is there a jQuery substitute for Prototypes Form.Request using AJAX?

Back in the prototype days, I used to post a form with its populated data simply by doing: $('form-id').request({ onComplete: function(response){ /* whatever */ } }) Now, I could always manually specify each field when building my request lik ...

Tips for dynamically changing the style (color/fill) of material-ui elements when generating them within a map function

I am struggling to dynamically change the style (colors) of elements in list items generated from a map function that includes rgb-color values. While using classes can work, trying to dynamically set the style based on the data/color provided in the objec ...

Allowing scroll events to flow through from a child <div> to <canvas> in Excalidraw

In my current project, I am utilizing Excalidraw to draw a layer of <div>s on top of the <canvas>. While everything is functioning well, I have encountered an issue with scrolling through the infinite canvas. When the mouse hovers over one of t ...

Glowing effects on svg shapes

I'm looking to add a pulsing light animation around an SVG half circle shape that I have created. After experimenting with CSS and Webkit, the closest I've come is achieving a pulsing light around the parent element, rather than the actual shape ...

Getting the value from a label and then setting it as the innerHTML of document.getElementById('label')

I have successfully implemented a JavaScript Google Maps functionality, but now I am facing an issue where I need to retrieve the type of HTML control and set it to JavaScript. Specifically, when attempting to extract the value from lblTitle, it is not f ...

AngularJS $location Redirect Error: Property 'path' Undefined

I'm struggling with an issue in my AngularJS code where I am trying to change the URL without reloading the page when a submit button is clicked. However, I keep getting a TypeError: Cannot read property 'path' of undefined in the console. ...

In certain situations, the JavaScript code runs either before or after the print dialog is displayed when using the window

I am facing an issue with the print function on my web page. I want to display a thank you message to the user after they have either printed or cancelled the print dialog. Below is a simplified version of the print function code: function printThenThank ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

Tips on ensuring the first column of an HTML table remains fixed in responsive design

I am trying to create a responsive HTML table where the first column remains fixed. I have a select box on my PHP page and I am using AJAX to display data from a database in the HTML table. However, when selecting a value in the select box in a responsiv ...

What is the way to change the background color using HTML5 getItem?

Here is the code I am currently using: $(this).css('backgroundcolor', localStorage.getItem('bgColorr') + " !important;"); When I execute this: alert( localStorage.getItem('bgColorr') + " !important;"); I receive the correc ...

The JavaScript code is unable to locate a specific variable in the file

Experiencing an issue with hasAttr.js where it is unable to locate the variable :jQuery. Assistance would be greatly appreciated. Just beginning my journey on the client side. ...

When using PHP files to send data through AJAX, be cautious of receiving only a "parsererror" message

After consulting with @skobaljic during a teamviewer session, it was discovered that I was not properly opening the html file in localhost, instead using the file system (file://...). I apologize for the confusion and time wasted. I am attempting to send ...

Retrieving a map using latitude and longitude coordinates saved in a database

I have a webpage with an embedded Google Map and a dropdown list of cities. The latitude and longitude values for each city are stored in a database. When a user selects a city from the dropdown list and clicks submit, I want the map to load with the corre ...