编写函数来计算字符串中字符的出现次数。 [JavaScript的]

时间:2015-07-12 08:54:44

标签: javascript

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

到目前为止,我已经到了,

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

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

4 个答案:

答案 0 :(得分:2)

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

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'));

如果你想要一个带有regexp的解决方案

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)应该是安全的

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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…}

答案 3 :(得分:0)

你在谈论那个:

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

这是在JS中创建函数的一种方法。开始的好点是here

请记住,JavaScript有更多的“创建”功能。