Number of occurrences of each character in the JavaScript calculation string

Source: Internet
Author: User
  code is as follows copy code

function CharCount (str) {
Replaces characters from a string with a regular match, using match () with a regular match. Length gets the number of occurrences of each character
str = str.replace (/s/ig, "");//Remove whitespace
var Strarr = Str.split ("");
var result = [],reg;
for (var i = 0; i < strarr.length; i++) {
if (Str.indexof (Strarr[i])!=-1) {
reg = new RegExp (Strarr[i], "IG");
Counts=str.match (reg). length;
str = str.replace (Reg, "");
Result.push (Strarr[i] + ":" + counts);
} www.111cn.net
}
return result;
}
var str= "This section of the site is dedicated to the JavaScript language itself, the parts that are not specific to Web p Ages or other host "
var result=charcount (str);
Console.log (Result.sort ());

Law 2:
Replaces characters from a string with a regular match, replacing the string length-the length of the string after the replacement, and the difference is the number of occurrences of the character

The code is as follows Copy Code

function CharCount (str) {
Replaces characters from a string with a regular match, replacing the string length-the length of the string after the replacement, and the difference is the number of occurrences of that character!
str = str.replace (/s/ig, "");//Remove whitespace
var Strarr = Str.split ("");
var result = [],beforelength, Afterlength, Reg;
for (var i = 0; i < strarr.length; i++) {
if (Str.indexof (Strarr[i])!=-1) {
Beforelength = Str.length;
reg = new RegExp (Strarr[i], "IG");
str = str.replace (Reg, "");
Afterlength = Str.length;
Result.push (Strarr[i] + ":" + (beforelength-afterlength));
} www.111cn.net
}
return result;
}
var str= "This section of the site is dedicated to the JavaScript language itself, the parts that are not specific to Web p Ages or other host "
var result=charcount (str);
Console.log (Result.sort ());

The 1th method uses fewer variables and is relatively well understood!

Related Article

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.