JavaScript计算字符串中每个字符出现次数的小例子_javascript技巧
程序员文章站
2022-04-28 11:35:13
...
代码如下:
function numInstring(str){
str=str.replace(/ /ig,"");
var strArr=str.split("");
var result=[],beforeLength,afterLength,reg;
for(var i=0;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));
}
}
return result;
}
var result=numInstring("This section of the site is dedicated to the JavaScript language itself, the parts that are not specific to Web pages or other host");
console.log(result);
/*result:
["T:17", "h:7", "i:9", "s:10", "e:14", "c:5", "o:8", "n:3", "f:3", "d:3", "a:9", "J:1", "v:1", "r:5", "p:4", "l:2", "g:3", "u:1", ",:1", "W:1", "b:1"]
*/
复制代码 代码如下:
function numInstring(str){
str=str.replace(/ /ig,"");
var strArr=str.split("");
var result=[],beforeLength,afterLength,reg;
for(var i=0;i
beforeLength=str.length;
reg=new RegExp(strArr[i],"ig");
str=str.replace(reg,"");
afterLength=str.length;
result.push(strArr[i]+":"+(beforeLength-afterLength));
}
}
return result;
}
var result=numInstring("This section of the site is dedicated to the JavaScript language itself, the parts that are not specific to Web pages or other host");
console.log(result);
/*result:
["T:17", "h:7", "i:9", "s:10", "e:14", "c:5", "o:8", "n:3", "f:3", "d:3", "a:9", "J:1", "v:1", "r:5", "p:4", "l:2", "g:3", "u:1", ",:1", "W:1", "b:1"]
*/
推荐阅读
-
python技巧 计算字符串中字母出现的次数并取出最大
-
用JS得到字符串中出现次数最多的字母_javascript技巧
-
将字符串中由空格隔开的每个单词首字母大写_javascript技巧
-
JavaScript实现计算字符串中出现次数最多的字符和出现的次数_javascript技巧
-
找出字符串中出现次数最多的字母和出现次数精简版_javascript技巧
-
JavaScript计算字符串中每个字符出现次数的小例子_javascript技巧
-
JavaScript indexOf方法入门实例(计算指定字符在字符串中首次出现的位置)_基础知识
-
js中通过split函数分割字符串成数组小例子_javascript技巧
-
JavaScript统计字符串中每个字符出现次数完整实例_javascript技巧
-
JavaScript计算字符串中每个字符出现的次数