Find difference between two strings in JavaScript

Elvis S. picture Elvis S. · Jul 18, 2019 · Viewed 13.1k times · Source

I need to find difference between two strings.

const string1 = 'lebronjames';
const string2 = 'lebronnjames';

The expected output is to find the extra n and log it to the console.

Is there any way to do this in JavaScript?

Answer

Nero picture Nero · Jul 18, 2019

    function getDifference(a, b)
    {
        var i = 0;
        var j = 0;
        var result = "";

        while (j < b.length)
        {
         if (a[i] != b[j] || i == a.length)
             result += b[j];
         else
             i++;
         j++;
        }
        return result;
    }
    console.log(getDifference("lebronjames", "lebronnjames"));