Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script:

span.highlight {
    background-color: #B4D5FF;
}

However, what if we want to highlight the differences between two strings? Take for example these two strings:

this is number 123

and

that is number 124

In the output, the differing parts should stand out. Can someone provide a solution for this?

span.highlight {background-color: #B4D5FF}
<p>this is number 123</p>
<p>
th<span class="highlight">at</span> is number 12<span class="highlight">4</span>
</p>

Answer №1

To extract each character from the new string, utilize the split() method to iterate through and compare them with the characters in the old string.

highlight($("#new"), $("#old"));

function highlight(newElem, oldElem){ 
  var oldText = oldElem.text(),     
      text = '';
  newElem.text().split('').forEach(function(val, i){
    if (val != oldText.charAt(i))
      text += "<span class='highlight'>"+val+"</span>";  
    else
      text += val;            
  });
  newElem.html(text); 
}
.highlight {background-color: #B4D5FF}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="old">this is number 123</p>
<p id="new">that is number 124</p>

You can also opt for a simpler code snippet like the one below:

highlight($("#new"), $("#old"));

function highlight(newElem, oldElem){ 
  newElem.html(newElem.text().split('').map(function(val, i){
    return val != oldElem.text().charAt(i) ?
      "<span class='highlight'>"+val+"</span>" : 
      val;            
  }).join('')); 
}
.highlight {background-color: #B4D5FF}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="old">this is number 123</p>
<p id="new">that is number 124</p>

If you prefer less usage of span tags, consider implementing the following code:

highlight($("#new"), $("#old"));

function highlight(newElem, oldElem){ 
  var oldText = oldElem.text(),     
      text = '',
      spanOpen = false;  
  newElem.text().split('').forEach(function(val, i){  
    if (val != oldText.charAt(i)){   
      text += !spanOpen ? "<span class='highlight'>" : "";
      spanOpen = true;
    } else {       
      text += spanOpen ? "</span>" : "";
      spanOpen = false;  
    }  
    text += val;
  });
  newElem.html(text); 
}
.highlight {background-color: #B4D5FF}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="old">this is number 123</p>
<p id="new">that is number 124</p>

Answer №2

In order to achieve this task, utilizing Javascript is necessary due to the complexity involved in detecting differences in text. As noted in other responses, simply comparing characters one by one is not sufficient.

Nevertheless, out of curiosity, I have created a basic implementation which can be viewed here:

CodePen

Below is the function responsible for identifying the differences between two texts:

function getDiff(text1,text2){
  //Receives two strings 
  //Returns an array showing the range of differences 
  //For example:
  // text1: "that is number 124"
  // text2: "this is number 123"
  //It will return:
  // [[2,4],[17,18]]
  //If the lengths are different, it only checks up to the end of text1
  //To perform case-insensitive comparison, convert the texts to lowercase before passing them 
  var diffRange = []
  var currentRange = undefined
  for(var i=0;i<text1.length;i++){
    if(text1[i] != text2[i]){
      //Difference found! 
      if(currentRange == undefined){
        //Start a new range 
        currentRange = [i]
      }
    }
    if(currentRange != undefined && text1[i] == text2[i]){
      //End of range! 
      currentRange.push(i)
      diffRange.push(currentRange)
      currentRange = undefined
    }
  }
  //Include any remaining range at the end 
  if(currentRange != undefined){
    currentRange.push(i)
    diffRange.push(currentRange)
  }
  return diffRange;
}

The getDiff function accepts two strings and returns where they differ. It functions properly when the strings are of equal length.

To utilize this function, simply do the following:

var text1 = "that is number 124"
var text2 = "this is number 123"
var diffRange = getDiff(text1,text2)

Feel free to modify the text within CodePen and observe its updates!

Once the ranges are obtained, the function generates the appropriate html, inserts <span> tags, and displays the element on the page. If the string lengths vary, consider using a Javascript diff library like (Jsdiff). This will provide a more robust solution.

Answer №3

Comparing text for differences is a more complex task than it may appear initially. The key is to determine how you want to identify each variation, such as:

  • Differences at the character level (123 vs. 124)
  • Additions of new text ('I have been to Sydney' vs. 'I have never been to Sydney).
  • Deletions of existing text (opposite of the previous example).

The challenge lies in detecting both the disparities and similarities between two strings. A simplistic approach would involve comparing the strings character by character. However, this method can lead to inaccuracies - with any addition or removal of even a single character causing the entire string to be flagged as different, despite most of it being identical to the original.

Your best course of action is to utilize an established text comparison library. Numerous options are available for JavaScript. One noteworthy suggestion is: https://github.com/kpdecker/jsdiff, which seems promising, although it might offer more functionality than necessary for your specific needs. In essence, relying on existing tools is recommended over attempting to create one from scratch, unless you're keen on diving deep into text parsing.

Answer №4

Indeed, the preceding response is accurate. However, if you find yourself needing to compare against a very specific format without relying on an external framework, you can utilize a javascript function like the one below to group your characters and apply CSS styling:

<html>

<style type="text/css">
.highlighted{
    background-color:blue;
}
</style>

<script type="text/javascript">

function init(){
    var output = document.getElementById("output");
    output.appendChild(highlightChanges("12777345aaaabbbbb","1277845abaababababababadsrfgadsg"));
}

var highlightChanges = function(str, compareStr){
    var strlength = str.length > compareStr.length ? compareStr.length : str.length;
    var allStr = document.createElement("span");
    var hl = null;
    var nohl = null;
    for(i = 0; i < strlength ; i++){
        if(str.charAt(i) != compareStr.charAt(i)){
            if(nohl != null){ 
                allStr.appendChild(nohl);
                nohl = null;
            }
            if(hl != null) hl.innerHTML += str.charAt(i);
            else{
                hl = document.createElement("span");
                hl.classList.add("highlighted");
                hl.innerHTML = str.charAt(i);
            } 
        }
        else{
            if(hl != null){
                allStr.appendChild(hl);
                hl = null;
            }
            if(nohl != null) nohl.innerHTML += str.charAt(i);
            else{
                nohl = document.createElement("span");
                nohl.innerHTML = str.charAt(i);
            } 
        }

        <!-- Fix by James Moberg to prevent premature end of comparison-->
        if(hl != null){
            allStr.appendChild(hl);
        } else if (nohl != null){
            allStr.appendChild(nohl);
        }
    }
    return allStr;
}
</script>

<body onload="init()">
    <div id="output"></div>
</body>

</html>

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

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Eliminate borders for text input in Bootstrap 3 styling

Trying to eliminate the top, right, and left borders for text input fields in Bootstrap 3. The selector being used is as follows: input[type="text"] { border-top: 0; border-right: 0; border-left: 0; } However, in Chrome, a faint thin line is ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

Ways to immediately display an uploaded image as the background on a canvas

Using TypeScript, I am attempting to set an uploaded image as the background of a canvas. However, I am facing an issue where the image only loads properly after the user has uploaded it two times. How can I ensure that the image has finished loading befor ...

Setting up a React application and API on the same port: A step-by-step guide

I have developed a React app that fetches data from a separate database through an API. While testing the app locally, it runs on one port while the API runs on another port. Since I need to make AJAX calls from the app to the API, I have to specify the ...

Generate a distinct link identifier using a loop iterator

I currently have a script that retrieves records from a MySQL database and needs to generate a unique ID dynamically for each record. Currently, I am using the <a> tag with "#" in the href attribute for testing purposes and would prefer to use links ...

"Encountering a null value when trying to pass parameters via jQuery ajax

Today, I decided to try using jQuery ajax for the first time with a jscript ajax call. I attempted to pass two values from one JSP page to another. Here is my approach: JspPage1.jsp $(function(){ var val1="Some value1"; var val2="Some value2"; $.ajax({ur ...

24-hour countdown tool featuring a visual progress bar

Currently, I am in the process of developing an application aimed at assisting individuals in either forming new habits or breaking old ones. In this application, I am looking to implement a countdown timer that ticks down daily; with the help of this help ...

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...

Overflowing text in the div element

Attempting to generate a sample document and aiming to enlarge the font-size by clicking the "Medium" & "Large" button. Encountering an issue where the font-size overlaps with other divs when pressing the "large" button, though not experiencing any proble ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...

Error encountered in Rails and Jquery when using dependent dropdowns: Uncaught TypeError - function is undefined

I have a challenge implementing 3 dependent dropdowns using collection_select and Jquery. My model, Categories, has fields for main, sub, and sub sub. Another model called product is associated with categories through the relationship where a category has_ ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Retrieving information from a server within several sections of a Flask application

Currently working on a project with Python using Flask and Jinja2, I am exploring ways to integrate a sidebar. Within the HTML pages, there is this snippet: {% include "sidebar.html" %} My objective for the sidebar file is to showcase a section highlight ...

Unable to initiate the server generated by the express.js generator

Currently, I am trying to set up an Express.js server using their generator. Following the documentation, I was able to successfully create the basic structure. However, when attempting to run the prescribed command (SET DEBUG=transcriptverificationserver: ...

WebView no longer refreshes when the document location is updated

I currently have a basic HTML/JavaScript application (without Phonegap) that I utilize alongside a native Android app and a WebView. When certain situations arise, I need to reload the current page in the JavaScript portion. On my old phone with Android 4 ...