What is the cleanest way of finding the position of the first difference in any two strings in Javascript?
var a = 'in the';
var b = 'in he';
findFirstDiffPos(a, b); // 3
var c = 'in the beginning';
findFirstDiffPos(a, c); // 6
What is the cleanest way of finding the position of the first difference in any two strings in Javascript?
var a = 'in the';
var b = 'in he';
findFirstDiffPos(a, b); // 3
var c = 'in the beginning';
findFirstDiffPos(a, c); // 6
You can simply iterate through your strings and check it character-by-character.
The output is
3 4 -1
:3
: because strings differ at position 34
: stringabcd
is a prefix ofabcde
, but they are of different length. The 4-th (0-based) character does not exist in stringabcd
. You can change this logic in accordance with your requirements-1
: strings are equalUpdate: As @torazaburo mentioned in comments, the code can be even easier - just make a loop until the
Math.max()
of their length. It will work becauses[i]
fori >= s.length
will returnundefined
and condition will result intrue
.The function can use some ES5 features:
This will automatically return at the end of the shortest string.
Edit
A bit of code golf leads to the following:
Or using ECMAScript 2015 findIndex:
But perhaps readability suffers. What is the criterion for selection?
For loop version of torazaburo's while loop effort (it's worthwhile using basic methods because they are usually much faster than iterators and not much more code, if any):
For fun, here's a one liner. It's not particularly readable though
Looping
The looping approach could be written a bit more succinctly as
According to jsperf, this alternative is an unsurprising 5-20 times faster than the other ones here.
Array#findIndex
Since we are trying to find the index at which a certain condition holds, this seems like a perfect application for
findIndex
:( We need the longer array to be the one we look up into, so we reverse the order if necessary. We use
[...a]
to convert the string into an array of characters.)Disclaimer: This is an ES6 interface that you will have to polyfill on IE (but not Edge).
This alternative is a staggering 20 times slower than the straight loop.
Recursion
Just for fun, here is a recursive solution:
Regexp
Also in the "just for fun" category, a regexp solution. We will construct a regexp of the form
/^(a(b(c)?)?)?/
from one string and match it against the other one, and check the length of the match.Even if we precompile the regexp, this is still five times slower than a plain old loop.