javascript - Detect position of first difference in 2 strings -


what cleanest way of finding position of first difference in 2 strings in javascript?

var = 'in the'; var b = 'in he'; findfirstdiffpos(a, b); // 3  var c = 'in beginning'; findfirstdiffpos(a, c); // 6  

you can iterate through strings , check character-by-character.

document.body.innerhtml += findfirstdiffpos("in he", "in the") + "<br/>";  document.body.innerhtml += findfirstdiffpos("abcd", "abcde") + "<br/>";  document.body.innerhtml += findfirstdiffpos("zxc", "zxc");    function findfirstdiffpos(a, b)  {     var shorterlength = math.min(a.length, b.length);       (var = 0; < shorterlength; i++)     {         if (a[i] !== b[i]) return i;     }       if (a.length !== b.length) return shorterlength;       return -1;  }

the output 3 4 -1:
3: because strings differ @ position 3
4: string abcd prefix of abcde, of different length. 4-th (0-based) character not exist in string abcd. can change logic in accordance requirements
-1: strings equal

update: @torazaburo mentioned in comments, code can easier - make loop until math.max() of length. work because s[i] i >= s.length return undefined , condition result in true.

document.body.innerhtml += findfirstdiffpos("in he", "in the") + "<br/>";  document.body.innerhtml += findfirstdiffpos("abcd", "abcde") + "<br/>";  document.body.innerhtml += findfirstdiffpos("zxc", "zxc");    function findfirstdiffpos(a, b)  {    var longerlength = math.max(a.length, b.length);    (var = 0; < longerlength; i++)    {       if (a[i] !== b[i]) return i;    }      return -1;  }


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -