-2

I am new to JavaScript, and I am trying to write a function that returns the number of occurrences of a given character in a string.

So far I've gotten,

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

if I run it in a JavaScript runner it works but I am not sure how to write it into a function. Any suggestions?

4 Answers4

3

Try this - doesn't use regexp because they can be a pain, so why use them unless you have to

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

if you DO want a solution with 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'));

But you need to be careful what needles you're looking for, e.g., . ( { [ ] } ) ! ^ $ are just some characters that will cause issues using the RegExp version - but searching for alphanumerics (a-z, 0-9) should be safe

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
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));
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…}
Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133
0

are you talking about that:

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

This is one way of how you create function in JS. Good point to start would be here.

Remember that JavaScript have more that one way of "creating" functions.

matekm
  • 5,990
  • 3
  • 26
  • 31