1

I am wondering if there is a way in JavaScript by which I can detect which part of my Strings makes them different from each other.

Let's say I have three strings as follows:

String1 = "Java1String"
String2 = "Java2String"
String3 = "Java3String"

If I choose my first String as a main one, the part which makes it different from the others is 1.

Is there any way using either JavaScript or jQuery by which I can find this part?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • 1
    You're looking for http://en.wikipedia.org/wiki/Levenshtein_distance – SLaks Sep 07 '14 at 02:31
  • @SLaks While related, I don't see how that gives the OP their answer – Ian Sep 07 '14 at 02:33
  • 11
    Are you going to show us your attempts to write the code or just let us do the work for you? Do you have any limitations on the inputs? Are they always strings? Always the same length? Always three of them? – DevlshOne Sep 07 '14 at 02:34
  • 1
    You need to look for "diff" algorithms. The solution will have nothing whatsoever to do with jQuery. – Pointy Sep 07 '14 at 02:59
  • My inputs always are String and there is no limitation. Actually I am parsing a big database of Strings and this is only a part of my work. I just needed to make sure if it is possible and see if there is something which can do that for me directly. Thanks to all. – user3321210 Sep 07 '14 at 03:10
  • @user3321210 Why would you downvote my answer? My code did exactly what you wanted. – Weafs.py Sep 08 '14 at 23:44
  • @chipChocolate.py I didn't! Thanks for your answer. I am a new user and not able to vote to answers! – user3321210 Sep 09 '14 at 19:31

3 Answers3

-1
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";

var j = 0;

for(var i = 0; i < String1.length; i++){
    if(String1.charAt(i) != String2.charAt(j))
        alert(String1.charAt(i) +"  !=  "+ String2.charAt(j));
        j++;
}

You can check out a demo of this code with this jsfiddle.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
-1
You can compare two strings like this. This will give you the characters which are different.


var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";

var j = 0;

for(var i = 0; i < String1.length; i++){
    if(String1.charAt(i) != String2.charAt(j))
        alert(String1.charAt(i) +"  !=  "+ String2.charAt(j));
        j++;
}

You can check out Demo of this code on this link

http://jsfiddle.net/enL9b3jv/1/

-3

The naive solution would be to convert each string into an array and iterate over the arrays, compare the character at each index until you find an index that doesn't match, and then write that index to a variable. Below is a Jsbin that does just that, but just as DevIshOne states, there are many questions to answer here...

http://jsbin.com/dugovemoxupu/1/edit

user2692837
  • 92
  • 1
  • 5