Home >Web Front-end >JS Tutorial >How to count the number of occurrences of each character in a string using js?
How to use js to count the number of occurrences of each character in a string?
JS method of counting the number of occurrences of each character in a string:
<script> /*这个字符串中的每个字每出现了多少次*/ var ary = "asasDFGHadDfFFhjkMNJGBHGDsdfghjfghjkdfghjkl"; var obj = {}; var i = 0; ary1 = ary.toLocaleLowerCase(); //将字符串转为小写 for(i = 0; i < ary1.length; i++) { key = ary1[i]; if(obj[key]) { //对象中有这个字母 obj[key]++; } else { //对象中没有这个字母,把字母加到对象中 obj[key] = 1; } } for(var key in obj) //遍历这个对象 { console.log(key + "这个字母出现了" + obj[key] + "次"); } </script>
Running results:
Recommended tutorial: "javascript basic tutorial"
The above is the detailed content of How to count the number of occurrences of each character in a string using js?. For more information, please follow other related articles on the PHP Chinese website!