Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JQuery plugin which compares two strings and highlights the differences

Tags:

jquery

Does anyone know of a JQuery plugin which compares two strings and highlights the differences. I've tried searching but although there is stuff out there I can't find a JQuery specific one. An example of a javascript one which does what I want is

Javascript Diff Algorithm

The problem with this one is that I want to implement it on a number of different strings at once (1 on each row of a table) which is why I wanted a Jquery one so I could use JQuerys each selector methods

like image 415
John Avatar asked Sep 19 '11 12:09

John


2 Answers

You can use the Javascript Diff Algorithm.
Check a demo at : http://jsfiddle.net/gion_13/Z3CRA/1/.

Instead of calling and aplying the function directly :

document.body.innerHTML = diffString(
   "The red brown fox jumped over the rolling log.",
   "The brown spotted fox leaped over the rolling log"
);

You can wrap it into a jquery plugin :

$.fn.pluginName = function(newValue){
    return this.each(function(){
        $(this).html(
            diffString(
                $(this).text(),
                newValue
            )
        );
    });
}
like image 82
gion_13 Avatar answered Nov 10 '22 18:11

gion_13


I wouldn't be looking for a jQuery plugin in your case. jQuery is a framework that helps handling the DOM changes and more, but there are not many string functions in jQuery.

Another one found through Google does almost the same as the one you reference: http://www.daftlogic.com/sandbox-javascript-compare-differences-between-strings.htm

edit It seems like the above mentioned script is the same one used by John Resig thanks for pointing that out danishgoel end edit

Your problem is that you want it to run over a list of items in a table? You would not need jQuery for the actual check on differences, but you can use a for loop around it, or a jQuery each call around it.

Like this HTML:

<ul id='sentences'>
    <li>sentence 1</li>
    <li>sentence 2</li>
    <li>sentence 3</li>
</ul>

and this JavaScript:

var default = "my sentence";
$('#sentences li').each(function(){
    var li = $(this);
    var result = $('<div/>').html( diffString( default, li.text() ) );
    li.append(result);
});

As you can see, here you use the jQuery each on a jQuery selector but you ask a regular JavaScript function. No need for a jQuery plugin to do exactly the same.

like image 33
Sander Avatar answered Nov 10 '22 20:11

Sander