Home > Web Front-end > JS Tutorial > Example of removing consecutive or all repeated characters from JS string

Example of removing consecutive or all repeated characters from JS string

亚连
Release: 2018-05-31 16:42:52
Original
1882 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(&#39;,&#39;); //[&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;]
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Vue.js实现图片的随意拖动方法

解决Vue 通过下表修改数组,页面不渲染的问题

vue2.0 axios跨域并渲染的问题解决方法

The above is the detailed content of Example of removing consecutive or all 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