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.