在javascript中查找字符串中的多个字符/字母

时间:2014-07-23 12:54:50

标签: javascript html

我想找到一些" a"字符串中的字符。理想情况下,我想得到一个输出作为一个数组,将在控制台中打印出如下:c - 15,b - 5,a - 4等。

<!DOCTYPE html>
<html>
<body>
<script>
function findStrings() {
mainString="Mazher Mahmood is a clever, canny and creative reporter who generates his own  stories. It's important to place that on record because, before we delve into his use of the darker journalistic arts, there should not be any illusion about his reporting skills. "

result=(mainString.split("a").length - 1);

console.log(result);

}
</script>

</body>
</html>

4 个答案:

答案 0 :(得分:0)

你只需要遍历每个字母,随时进行检查并将其附加到对象上:

function findStrings() {
    var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        ret = {};
    for(i=0; i<letters.length; i++){    
        ret[letters[i]]=(mainString.split(letters[i]).length - 1);
    }
    console.log(ret);
}

findStrings();

如果您想明确检查任何其他字符,只需将它们添加到letters字符串的末尾。

JSFiddle

答案 1 :(得分:0)

如果你只想计算字母/字符的出现次数,你只需循环遍历字符串:

function findStrings() {    
    var mainString="Mazher Mahmood is a clever, canny and creative reporter who generates his own  stories. It's important to place that on record because, before we delve into his use of the darker journalistic arts, there should not be any illusion about his reporting skills. "

    var findings = {};
    for(var i=0; i<mainString.length; i++){
        if(typeof( findings[mainString[i]] ) == "undefined"){
            findings[mainString[i]] = 0;
        }
        findings[mainString[i]]++;
    }

    for(var sym in findings){
        console.log("The character "+sym+" has been found "+findings[sym]+" times");
    }
}

findStrings();

注意: oGeez的答案仅计算特定字符的出现次数,而我的答案计算所有出现的字符的出现次数。你的问题对你实际想要达到的目标不够清楚。

JSFiddle:http://jsfiddle.net/A4WWN/

答案 2 :(得分:0)

你可以算这样:

mainString="Your Big String";

function count(str) {
  var chars = {};
  var astr = str.split("");

  for (var i = 0, len = astr.length; i < len; i++) {
    var letter = astr[i];
    chars[letter] = chars.hasOwnProperty(letter) && chars[letter] + 1 || 1;
  }
  return chars;
}

console.log(count(mainString));

请注意,通过这种方式,您将计算每个字符的出现次数,包括空格,逗号等。

答案 3 :(得分:0)

试试这个:

function getCharAppearences(str) {
    var character,result = {};
    for(var i = 0; i < str.length; i++) {
        character = str.charAt(i);
        result[character] = result[character] + 1 || 1;
    }
    return result;
}

Fiddle