I know how to highlight part of a text with CSS using this script:
span.highlight {
background-color: #B4D5FF;
}
Now I want to highlight the difference of two strings. For example given the following two strings:
this is number 123
and
that is number 124
I need to have a text highlighted like what I've shown here. Could somebody help me achieve 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>
You need to get all character of new string using split()
method and iterate every character and compare it with character of 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>
Also you can use simpler code as shown in bottom
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>
And if you want to use less span check bottom 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With