So you'll have to use Javascript to accomplish this, since it involves a fair bit of logic. As mentioned in the other answer(s), detecting difference in text is a little bit more complicated than just checking character by character.
However, for curiosity's sake, I put together this naive implementation:
CodePen
Here's what the function that gets the differences looks like:
function getDiff(text1,text2){
//Takes in two strings
//Returns an array of the span of the differences
//So if given:
// text1: "that is number 124"
// text2: "this is number 123"
//It will return:
// [[2,4],[17,18]]
//If the strings are of different lengths, it will check up to the end of text1
//If you want it to do case-insensitive difference, just convert the texts to lowercase before passing them in
var diffRange = []
var currentRange = undefined
for(var i=0;i<text1.length;i++){
if(text1[i] != text2[i]){
//Found a diff!
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
}
}
//Push any last range if there's still one at the end
if(currentRange != undefined){
currentRange.push(i)
diffRange.push(currentRange)
}
return diffRange;
}
The function getDiff
takes in two strings, and returns the ranges at which they differ. This works great as long as the two strings are of the same length.
So to use this, all I do is:
var text1 = "that is number 124"
var text2 = "this is number 123"
var diffRange = getDiff(text1,text2)
Try changing the texts there in the CodePen and watch it update!
Once it gets these ranges, it then generates the html and inserts the <span>
tags, and adds the element to the page. If you know your strings will always be the same, this could be enough. Otherwise, it would be best to look at a Javascript diff libary! (Jsdiff seems like a good library)