<html>
<head>
<title>利用正则表达法除去字符串中的重复字符</title>
</head>
<body>
<script language="网页特效">
str = "google"
str1 = str.replace(/(.).*/g,"$1")
document.write(str + "<br>");
document.write(str1);
</script>
</body>
</html>
去除重复字符实例二
一段实现除去字符串中重复的js代码
function okd(){
var o = document.getelementsbyname("number")[0];
var array = new array();
var k =0;
for(var i=0;i<o.value.length;i++){
if(array == "" || array.tostring().match(new regexp(o.value.charat(i),"g")) == null){
array[k] =o.value.charat(i);
array.sort();
k++;
}
}
alert(array.tostring());
}
再来看一个利用数组过滤重复字符的实例
<script language="javascript">
<!--
//字符串转成数组
function str2array(){
var str = "a1a1a2s2a1a3a3a1a2";//a1a2s2a3 a1a2s2a3
var arr = new array(str.length/2);
var j = 0;
for (var i = 0; i < str.length; i+=2)
{
arr[j]= str.charat(i) + str.charat(i+1);
j++;
}
return arr;
}
function compare(o, v){
if (o == v){
return true;
} else{
return false;
}
}//数组元素比较
//排除数组中相同的元素
var arr = str2array();
for (var j = 0; j < arr.length; j++)
{
for (var k = j +1; k < arr.length; k++)
{
if (compare(arr[j], arr[k])){//元素值相等
arr[k] = "";
continue;
}
}
}//格式化输出结果
var str = "";
for (var z = 0; z < arr.length; z++)
{
if (arr[z] == ","){
continue;
} else{
str += arr[z];
}
}
document.write(str);
//-->
</script>