Home > Web Front-end > JS Tutorial > body text

Remove duplicate characters from JS string

php中世界最好的语言
Release: 2018-03-29 09:21:05
Original
2382 people have browsed it

这次给大家带来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
Copy after login

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
Copy after login

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

 js重复某个字符串n次

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

 字符串转数组

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

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

推荐阅读:

use怎么注册Vue的全局组件

Vue.js自定义事件如何进行表单输入组件

The above is the detailed content of Remove duplicate characters from JS string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template