本文實例講述了JS實現(xiàn)為排序好的字符串找出重復(fù)行的方法。分享給大家供大家參考,具體如下:
實現(xiàn)這樣一個需求,在一個Editplus文檔中,有很多行10位的數(shù)字,這些數(shù)字已經(jīng)排好序了。
比如:
1234567890
1234567891
1234567892
1234534124
1234614124
4321412414
5636373573
有什么辦法能方便的找出兩行至少前7位相同的數(shù)字嗎?
比如,上面的數(shù)字中,能夠找出
1234567890
1234567891
1234567892
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<style type="text/css">
div{ float:left; }
#divCenter{ padding-top:100px;margin:0 50px; }
.txt{width:200px;height:200px;}
#txtOldData{background-color:#A6CAF0;}
#txtAnswer{background-color:#EBA9A6;}
</style>
<script type="text/javascript">
function test() {
var arr = document.getElementById("txtOldData").value.replace(/ +/g, '').split("\n");
var tempStr = arr[0].substring(0, 7);
var compareLen = 7, equalNum = 0;
var answer = "";
for (var i = 1; i < arr.length; i++) {
if (arr[i].substring(0, 7) == tempStr) {
if (equalNum == 0)
answer += arr[i - 1] + "\n";
answer += arr[i] + "\n";
equalNum++;
} else {
tempStr = arr[i].substring(0, 7);
equalNum = 0;
}
}
document.getElementById("txtAnswer").value = (answer);
}
</script>
</head>
<body>
<div>
請輸入數(shù)值:<br />
<textarea id="txtOldData" class="txt">
1234567890
1234567891
1234567892
1234534124
1234614124
4321412414
5636373573
</textarea>
</div>
<div style="padding-top:90px;padding" >
<input type="button" value="測試==>" onclick="test()" />
</div>
<div>
結(jié)果:<br />
<textarea id="txtAnswer" class="txt"></textarea>
</div>
</body>
</html>
希望本文所述對大家JavaScript程序設(shè)計有所幫助。