Home  >  Article  >  Web Front-end  >  How to remove all duplicate characters in JS

How to remove all duplicate characters in JS

php中世界最好的语言
php中世界最好的语言Original
2018-03-28 17:25:491786browse

这次给大家带来JS怎样实现剔除全部的重复字符,JS实现剔除全部的重复字符的注意事项有哪些,下面就是实战案例,一起来看一下。

js字符串去除连续重复字符

()和\number 配合使用表示重复正则第number个括号内匹配到的内容,如:(\d)\1表示重复第一个匹配块(\d)即等价于如果(\d)匹配到a,则表达式为aa

相应的可以:(some)\1* 或(some)\1+或(some)\1? 表示重复第一个匹配快得到的内容 任意次或者 至少一次或 一次or零次

  var s = "1122333455";
     var s1 = s;
     var c;
     var cc = s.match(/(\d)\1+/g);    //11,22,333,55 当然这里用()\1*也会可以(因为下面是替换):11,22,333,4,55
     for(var i = 0;i<cc.length;i++){
         c = cc[i].substring(0,1);
         s1 = s1.replace(cc[i],c);
    }
    alert(s1);   //12345

js字符串去除全部重复字符,并把最终字符串排序

     var s = "1234321abaccc";
     var s1 = s.split("").sort().join("");
     var cc = s1.match(/(.)\1+/g);    //11,22,33,aa,ccc 当然这里用()\1*也会可以(因为下面是替换):11,22,33,4,aa,b,ccc
     for(var i = 0;i<cc.length;i++){
         c = cc[i].substring(0,1);
         s1 = s1.replace(cc[i],c);
     }
    alert(s1);    //1234abc

 PS:下面看下js重复某个字符串n次 | 字符串转数组

 js重复某个字符串n次

function repeat(str , n){
return new Array(n+1).join(str);
}
console:
repeat("a", 3); //aaa

 字符串转数组

var sa="ABCD";
var newStr=Array.prototype.join.call(sa); //A,B,C,D
newStr.split(','); //['A','B','C','D']

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

在vue里如何使用xe-utils

vue项目打包后刷新404怎么处理

The above is the detailed content of How to remove all duplicate characters in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn