首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何比较两个文本区域并检查Javascript中具有相同字符串和相同位置的重复项?

如何比较两个文本区域并检查Javascript中具有相同字符串和相同位置的重复项?
EN

Stack Overflow用户
提问于 2018-07-12 22:06:14
回答 2查看 136关注 0票数 -1

我想比较两个文本区域。对文本区域1中具有相同字符串和位置的所有单词/字符串进行计数。

例如:

Textarea 1:

苹果

香蕉橙

Textarea 2:

苹果橙色

香蕉

在这个例子中,苹果和香蕉被认为是正确的,具有相同的字符串和正确的位置,而橙色是错误的。

这在javascript中是可能的吗?请告诉我正确的方向。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-13 04:26:05

这里有另一种方法:

$(document).ready(function(){

	$(".btn").click(function () {
    
    var msg1Lines = $(".area1").val().split("\n"); //split text into lines
    var msg2Lines = $(".area2").val().split("\n"); //split text into lines
    var stopIndex;
    
    if(msg1Lines.length > msg2Lines.length) //determine which text area has more lines
    {
    		stopIndex = msg2Lines.length;
    }
    else
    {
    		stopIndex = msg1Lines.length;
    }
    
    for(i = 0; i < stopIndex; i++) //for each line in the message with the fewest number of lines
    {
        var msg2LineWords = msg2Lines[i].split(" ");
        for(j = 0; j < msg2LineWords.length; j++) //for each word in 2nd textarea
        {
          if(msg1Lines[i].search(msg2LineWords[j]) != msg2Lines[i].search(msg2LineWords[j])) //if word does not start at same index in both text areas
          {
               $(".difference").val($(".difference").val() + msg2LineWords[j] + "\n"); //display results in third textarea
          }
        }
       
    }
   
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="area1">
Apple
Banana Orange
</textarea>

<textarea class="area2">
Apple Orange
Banana
</textarea>

<button class="btn" style="display: block; margin-top: 10px;">Test</button>

<p style="display: block; margin-top: 10px;">
Incorrect: 
</p>
<textarea class="difference" style="display: block; margin-top: 10px;"></textarea>

票数 0
EN

Stack Overflow用户

发布于 2018-07-12 22:12:10

首先,将两个文本区域另存为字符串,然后通过拆分运行它们。之后,通过for each循环运行它们,以检查字符串是否匹配。

textArea1 = "Apple Banana Orange";
textArea2 = "Apple Orange Banana";

array1 = textArea1.split(" ");
array2 = textArea2.split(" ");

for (i = 0; i < array1.length; i ++) {
  if(array1[i] == array2[i]) {
    console.log("Match");
  } else {
    console.log("Mismatch");
  }
}

或者诸如此类的东西;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51307762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档