我想比较两个文本区域。对文本区域1中具有相同字符串和位置的所有单词/字符串进行计数。
例如:
Textarea 1:
苹果
香蕉橙
Textarea 2:
苹果橙色
香蕉
在这个例子中,苹果和香蕉被认为是正确的,具有相同的字符串和正确的位置,而橙色是错误的。
这在javascript中是可能的吗?请告诉我正确的方向。
发布于 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>
发布于 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");
}
}
或者诸如此类的东西;
https://stackoverflow.com/questions/51307762
复制相似问题