Home > Web Front-end > JS Tutorial > How to remove consecutive and repeated characters from JS string

How to remove consecutive and repeated characters from JS string

小云云
Release: 2018-03-12 09:26:22
Original
2418 people have browsed it

本文主要和大家分享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(&#39;,&#39;); //[&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;]
Copy after login

The above is the detailed content of How to remove consecutive and repeated 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