Home > Web Front-end > JS Tutorial > body text

How to count the number of occurrences of each character in a string using js?

coldplay.xixi
Release: 2020-06-20 15:55:15
Original
12683 people have browsed it

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>
Copy after login

Running results:

How to count the number of occurrences of each character in a string using js?

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template