比较js中的两个字符串并找出差异

时间:2018-07-02 11:59:34

标签: javascript arrays string

如何纯粹比较两个字符串,并提供特定的结果,例如突出显示第二个字符串中的多余单词,错误单词和跳过单词。例如。

var x = "This is the first original string in javascript language." </br>
var y = "This is not the first org string in language."

diff =  wrong word ="org"<br>
        Extra word ="not"<br>
        skip word ="javascript"

//这是我的代码片段,但在某些情况下我的程序失败

  var x = "here is some value of string";
  var y = "here is the some val string";
  var k=0; 
  var SkipWrd="";
 for(var i=0; i<y.length;i++){ 
    var sktmp="";
    var swtmp=0;
     for(var j=0; j<=2;j++) { 
         if(x[k]!="undefined"){ 
             if(y[i]==x[k+j]){  

                 SkipWrd+=sktmp;
                 skip+=swtmp;
                 H_wrd +=  typ_wrd[i]+" ";
                 org_para+= sktmp+x[k+j]+" ";

                 k+=j+1;
                 break;
             }
            else{
             sktmp+= "<mark>"+ x[k+j]+" "+ "</mark>";
             swtmp++; 
             if(j==2 && y[i]!=x[k+j]){
                 err++;
                 Err_Wrd+=y[i]+" ";
                 H_wrd += "<span id='H-Err'>" + typ_wrd[i] + "</span> ";
                 org_para+="<span id='O-Err'>" +x[k]+" "+ "</span> ";

                 k++;
             }
            }
        } 
     }
 }

1 个答案:

答案 0 :(得分:1)

我使用的是逐词比较方法,而不是您使用的逐字符方法。总体逻辑是相似的。 下面的代码适用于您的示例,但是还有很多情况可能会出错。

var x = "This is the first original string in javascript language.";
var y = "This is not the first org string in language.";

x=x.split(' ');
y=y.split(' ');

var i=0,j=0;
while (1) {
  if (!x[i] || !y[j]) break;
  
  if (x[i] == y[j]) {
    i++;
    j++;
    continue;
  }
  
  if (x[i] == y[j+1]) {
    console.log('Extra word : ', y[j]);
    i++;
    j+=2;
    continue;
  }
  
  if (x[i+1] == y[j]) {
    console.log('Skip word: ', x[i]);
    i+=2;
    j++;
    continue;
  }
  
  if (x[i+1] == y[j+1]) {
    console.log('Wrong word: ', y[j]);
    i++;
    j++;
    continue;
  }
}