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?
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])));
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!
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