【问题标题】:Writing a function to count the occurrences of a character in a string. [JavaScript] [duplicate]编写一个函数来计算字符串中某个字符的出现次数。 [JavaScript] [重复]
【发布时间】:2015-09-30 16:42:04
【问题描述】:

我是 JavaScript 新手,我正在尝试编写一个函数来返回字符串中给定字符的出现次数。

目前为止,

var str = "My father taught me how to throw a baseball.";
var count = (str.match(/t/g) || []).length;
alert(count);

如果我在 JavaScript 运行程序中运行它,它可以工作,但我不确定如何将它写入函数。有什么建议吗?

【问题讨论】:

  • 您是否尝试过学习该语言的基础知识?

标签: javascript


【解决方案1】:

试试这个 - 不使用正则表达式,因为它们可能会很痛苦,所以除非你必须这样做,否则为什么要使用它们

var str = "My father taught me how to throw a baseball.";

function getCount=function(haystack, needle) {
    return haystack.split(needle).length - 1;
}

alert(getCount(str, 't'));

如果您确实想要使用正则表达式的解决方案

var str = "My father taught me how to throw a baseball.";

function getCount=function(haystack, needle) {
    var re = new RegExp(needle, 'g');
    return (haystack.match(re) || []).length;
}

alert(getCount(str, 't'));

但是您需要注意您要查找的 needles 是什么,例如 . ( { [ ] } ) ! ^ $ 只是一些会导致使用 RegExp 版本出现问题的字符 - 但搜索字母数字 (az, 0-9) 应该是安全

【讨论】:

    【解决方案2】:

    你在说那个吗:

    function len(inputString) {
        return (inputString.match(/t/g) || []).length;
    }
    

    这是在 JS 中创建函数的一种方式。好的起点是here

    请记住,JavaScript 有不止一种“创建”函数的方式。

    【讨论】:

      【解决方案3】:
      function getOccurencies(b){
       var occur = {};
        b.split('').forEach(function(n){
          occur[n] = b.split('').filter(function(i){ return i == n; }).length;
        });
        return occur;
      }
      
      getOccurencies('stackoverflow is cool') // Object {s: 2, t: 1, a: 1, c: 2, k: 1…}
      

      【讨论】:

        【解决方案4】:
        var str = "My father taught me how to throw a baseball.";
        var getCount=function(str){
            return (str.match(/t/g) || []).length;
        };
        alert(getCount(str));
        

        【讨论】:

        • 正是我想要的。谢谢=)
        猜你喜欢
        • 2017-03-04
        • 2017-10-09
        • 2010-11-12
        • 1970-01-01
        • 2013-12-25
        • 2023-02-04
        • 1970-01-01
        相关资源
        最近更新 更多