Design & Download
Your JS Library
in Seconds!!!

Snippet: indexOfDiff() - Start of the Difference

Written by Christopher West (cwest) on August 09, 2016.
Determine where 2 strings begin to differ from each other.
function indexOfDiff(str1, str2) {
  var splitLen = Math.ceil(Math.min(str1.length, str2.length) / 2),
      s1_1 = str1.slice(0, splitLen), s2_1 = str2.slice(0, splitLen);
  return str1 != str2
    ? splitLen
      ? s1_1 != s2_1
        ? splitLen - 1 && indexOfDiff(s1_1, s2_1)
        : (indexOfDiff(str1.slice(splitLen), str2.slice(splitLen)) + splitLen)
      : 0
    : -1;
}

indexOfDiff(...) API Documentation

Description

Determines where 2 strings begin to differ from each other. This function has been optimized to work with both small and large strings.

Parameters

  1. str1 {string}:
    A string to be compared to another string.
  2. str2 {*}:
    A string to be compared to str1.

Returns

If str1 matches str2, -1 will be returned. In all other cases, the first index at which the corresponding character in str1 is not the same as that found in str2 will be returned.

Example

console.log(YourJS.indexOfDiff('', ''));  // -> -1
console.log(YourJS.indexOfDiff('Cool', 'Cool'));  // -> -1
console.log(YourJS.indexOfDiff('Cool beans', 'Cool'));  // -> 4
console.log(YourJS.indexOfDiff('Cool beans', 'Cool jeans'));  // -> 5
console.log(YourJS.indexOfDiff(Math.PI + '', '3.14159'));  // -> 7