Javascript计数字符不区分大小写

时间:2016-11-19 17:58:38

标签: javascript arrays loops

我必须计算每个字母出现在字符串中的次数。 不区分大小写。
例如:
var str =“aaaAAAbbB”
会打印“A:6,B:3”
这就是我所拥有的,但它将小写和大写分开。

        var string = document.getElementById("text").value
        var counts = {};
        var ch, index, length, count;
        for (index = 0, length = string.length; index < length; index++)
        {
            ch = string.charAt(index);
            count = counts[ch];
            counts[ch] = count ? count + 1 : 1;
        }
        for (ch in counts)
        {
            console.log(ch+" count: "+counts[ch]);
        }

4 个答案:

答案 0 :(得分:7)

您可以将字符更改为upperlower以便计算。

ch = string.charAt(index).toUpperCase();
//                       ^^^^^^^^^^^^^^

var string = "aaaAAAbbB";
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++) {
    ch = string.charAt(index).toUpperCase();
    count = counts[ch];
    counts[ch] = count ? count + 1 : 1;
}
for (ch in counts) {
    console.log(ch + " count: " + counts[ch]);
}

比较风格

var string = "aaaAAAbbB",
    counts = {};

string.split('').forEach(function (c) {
    counts[c.toUpperCase()] = (counts[c.toUpperCase()] || 0) + 1;
});

console.log(counts);

答案 1 :(得分:0)

为了解决您的问题,我只想使用

string.toLowerCase();

然后你可以计算每个角色。

我修改了你的代码:

    var string = document.getElementById("text").value.toLowerCase();
    var counts = {};
    var ch, index, length, count;
    for (index = 0, length = string.length; index < length; index++)
    {
        ch = string.charAt(index);
        count = counts[ch];
        counts[ch] = count ? count + 1 : 1;
    }
    for (ch in counts)
    {
        console.log(ch+" count: "+counts[ch]);
    }

答案 2 :(得分:0)

您可以使用.toLowerCase()方法,将所有文本更改为小写 然后您的代码应如下所示:

    var string = document.getElementById("text").value.toLowerCase()
    var counts = {};
    var ch, index, length, count;
    for (index = 0, length = string.length; index < length; index++)
    {
        ch = string.charAt(index);
        count = counts[ch];
        counts[ch] = count ? count + 1 : 1;
    }
    for (ch in counts)
    {
        console.log(ch+" count: "+counts[ch]);
    }

答案 3 :(得分:0)

&#13;
&#13;
var str = "aaaAAAbbB";
var result = {};
//lowercase so they are all insensative and split to get an array.  loop over the array
str.toLowerCase().split('').forEach(function(element, index, array){
  //if not processed before, perform count
  if (!result[element]) {
    result[element] = array.filter(function(element2){ return element2 === element; }).length;
  }
});

console.log(result);
&#13;
&#13;
&#13;