Search code examples
javascriptarrayscomparesentence

Javascript: How to compare to sentences word to word


I'm sort of creating typing tutor with custom options.

Not a professional (don't get mad at me for being wrong-person-wrong place) but thanks to helpful forums like stackoverflow.com and contributing traffic/people I'm able to pull it out in a day or two.

Directly now, here!

    while (i < len+1){
      if(boxarray[i] == orgarray[i]){
    ++i;
        actualScore = i - 1;
      }

I've searched already, '==' operator is of no use, I will not go for JSON.encode. I met similar solution at this page . But in my case I've to loop through each word while comparing two sentences. Detail is trivial, if someone please help me solve above, I won't return with complain on the same project, promise.

Okay I'm putting more code if it can help you help me.

    var paratext = document.getElementById('typethis').innerHTML;    
    var orgstr = "start typing, in : BtXr the yellow box but. please don't shit." ;
    var boxtext = document.getElementById('usit').value; 
    var endtrim = boxtext;
    var actualScore;
    var orgarray = listToArray(orgstr," ");
    var boxarray = listToArray(boxtext," ");
    var len = boxarray.length;
    var i = 0;
    var actualScore; //note var undefined that's one mistake I was making [edit]
    if(orgstr.indexOf(boxtext) !== -1){
    while (i < len+1){
      if(boxarray[i] == orgarray[i]){
    ++i;
        actualScore = i - 1;
       }
     }      
    alert(actualScore);
    }

Solution

  • If I follow what you're after how about something like this:

    http://jsfiddle.net/w6R9U/

    var s1 = 'The dog sleeps';
    var s2 = 'the dog jogs';
    
    var s1Parts= s1.split(' ');
    var s2Parts= s2.split(' ');
    
    var score = 0;
    
    for(var i = 0; i<s1Parts.length; i++)
    {
         if(s1Parts[i] === s2Parts[i])
             score++;   
    }
    

    "The dog sleeps" and "the dog sleeps" results in a score of 2 because of case (which could be ignored, if needed). The example above results in a score of 1. Could get a percent by using the length of the sentences. Hope this helps! If nothing else might get you started.