Example of JS string removing consecutive or all repeated characters, js string character instance

Source: Internet
Author: User

Example of JS string removing consecutive or all repeated characters, js string character instance

Remove consecutive duplicate characters from js strings

() And \ number are used together to indicate the Matching content in the parentheses of the repeat regular number, for example: (\ d) \ 1 indicates repeat the first matching block (\ d) it is equivalent to the expression aa if (\ d) matches.

The corresponding values can be: (some) \ 1 * or (some) \ 1 + or (some) \ 1? Indicates repeat the first match to obtain the content any time or at least once or zero.

Var s = "1122333455"; var s1 = s; var c; var cc = s. match (/(\ d) \ 1 +/g); // 11,22, 333,55 of course here () \ 1 * can also be used (because the following is a replacement): 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

Remove all duplicate characters from the js string and sort the final string

Var s = "1234321 abaccc"; var s1 = s. split (""). sort (). join (""); var cc = s1.match (/(.) \ 1 +/g); //, 33, aa, ccc, of course, here () \ 1 * can also be used (because it is replaced below):, 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: Let's take a look at js repeat a string n times | string to array

Js repeats a string n times

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

String to array

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

Summary

The above is an example of how to remove consecutive or all repeated characters from JavaScript strings. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.