Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the position of the first occurrence of the difference between the two string?

Tags:

javascript

For example, Hello World! and Hi World! - the first occurrence of the difference is at the second character. What would be the JavaScript/jQuery function?

like image 644
Yuto Avatar asked Apr 18 '11 06:04

Yuto


2 Answers

Assuming, like other answers, that matching strings return -1:

// Find common prefix of strings a and b.
var prefix = function(a,b){
    return a && a[0] === b[0] ? a[0] + prefix(a.slice(1), b.slice(1)) : '';
};

// Find index of first difference.
var diff = function(a,b){
    return a===b ? -1 : prefix(a,b).length;
};

var tests = [
    ['Hello World!', 'Hi World!'],
    ['aaabab', 'aaabzbzz'],
    ['', ''],
    ['abc', 'abc'],
    ['qrs', 'tu'],
    ['abc', ''],
    ['', 'abc']
];

console.log('diff', tests.map(test => diff(test[0], test[1])));

// Or just count up to the first difference
// Trickier nested ternary to handle the -1 however.

var diff2 = function(a,b){
    return a === b ? -1 : a[0] === b[0] ? 1 + diff2(a.slice(1), b.slice(1)) : 0;
};

console.log('diff2', tests.map(test => diff2(test[0], test[1])));
like image 70
1983 Avatar answered Oct 08 '22 03:10

1983


Maybe something like this? It returns, in that order, the position of the first difference if there's any, the length of the shortest string if those are different, or -1 if everything is equal.

function findDiff(a, b) {
    a = a.toString();
    b = b.toString();
    for (var i = 0; i < Math.min(a.length, b.length); i++) {
        if (a.charAt(i) !== b.charAt(i)) { return i; }
    }
    if (a.length !== b.length) { return Math.min(a.length, b.length); }
    return -1;
}

Thanks Phil for the suggestions!

like image 33
Aleadam Avatar answered Oct 08 '22 04:10

Aleadam