JS判断一个字符串是否含有重复字符
2个回答
展开全部
第一种实现方式,直接用“,”拆分字串为数组,用for循环依次判断每个字符是否有重复: <html> <head> <script language="javascript"> function CheckRepeat(){ var data = document.getElementById("txtData").value; var r = getRepeatData(data); alert(r); } function getRepeatData(input){ var ary = input.split(","); var rdata = {}; for(var i in ary){ var c = ary[i]; rdata[c] ? (rdata[c]++) : (rdata[c]= 1) } var strResult = ""; for(var k in rdata){ if(rdata[k] > 1) strResult += k + "出现了" + rdata[k] + "次,"; } strResult && (strResult.replace(/,$/,"")); return strResult ? strResult : "字串(\"" + input + "\")中没有重复项!" } </script> </head> <body > <input type="text" id="txtData" size="80" value="1,2,3,4,1,5,2,6,1,7,2"/> <button onclick="CheckRepeat();">检查重复</button> </body></html>第二种方式,用正则表达式实现: <html> <head> <script language="javascript"> function CheckRepeat(){ var data = document.getElementById("txtData").value; var r = getRepeatData(data); alert(r); } function getRepeatData(input){ var temp = "," + input + ","; var reg = /([^,]+)(?=.*\1,)/g; var result = []; var exsits = {}; while(reg.exec(temp)){ var c = RegExp.$1; if(!exsits[c]){ exsits[c] = true; var count = temp.split("," + c + ",").length - 1; result.push(c + "出现了" + count + "次"); } } return result.length ? result.join(",") : "字串(\"" + input + "\")中没有重复项!" ; } </script> </head> <body > <input type="text" id="txtData" size="80" value="1,2,3,4,1,5,2,6,1,7,2"/> <button onclick="CheckRepeat();">检查重复</button> </body></html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询