JS使用正则表达式除去字符串中重复字符的方法

JavaScript030

JS使用正则表达式除去字符串中重复字符的方法,第1张

本文实例讲述了JS使用正则表达式除去字符串中重复字符的方法。分享给大家供大家参考,具体如下:

这里演示一个简单的JavaScript正则表达式实例,将一串含有重复字符串中的多余字符滤除掉,请运行查看效果。

具体代码如下:

<html>

<head>

<title>利用正则表达法除去字符串中的重复字符</title>

</head>

<body>

<script

language="javascript">

str

=

"Google"

str1

=

str.replace(/(.).*\1/g,"$1")

document.write(str

+

"<br>")

document.write(str1)

</script>

</body>

</html>

运行结果如下:

Google

Gogle

希望本文所述对大家JavaScript程序设计有所帮助。

第一种实现方式,直接用“,”拆分字串为数组,用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] = truevar count = temp.split("," + c + ",").length - 1result.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>

var str ='jdsdjsjdj'

var ss = cf(str)

console.log(ss) //打印结构是{j: 4, d: 3, s: 2, num: 4, key: "j"}

console.log(ss.key)//打印结果是 j

console.log(ss.num)//打印结果是 4