代码如下 | 复制代码 |
function charCount(str) { // 用正则匹配将各个字符从字符串中替换掉,直接用正则匹配的match().length获取每个字符出现的次数 str = str.replace(/s/ig, "");//去除空格 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 pages or other host" var result=charCount(str); console.log(result.sort()); |
法2:
用正则匹配将各个字符从字符串中替换掉,替换前字符串长度-替换后字符串长度,差值即为该字符出现的次数
代码如下 | 复制代码 |
function charCount(str) { // 用正则匹配将各个字符从字符串中替换掉,替换前字符串长度-替换后字符串长度,差值即为该字符出现的次数! str = str.replace(/s/ig, "");//去除空格 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 pages or other host" var result=charCount(str); console.log(result.sort()); |
第1种方法用的变量较少,也相对比较好理解!
时间: 2024-10-25 15:33:34