Count occurrences of something in a string

Posted: February 16, 2010 in Uncategorized

I just wanted to make a quick post about a very cool little piece of code I’ve recently found. Thanks to my Web Design teacher for showing me the JS version. If you would like to find out how many occurences of something are in a string, for example, how many of the letter ‘e’ is in the string ‘Hello world, this is pretty cool, don’t you think?’, you could use this code snippet.

In Javascript this is a little bit easier. You will need this function in your JS code somewhere.

String.prototype.count_occurences = function(char)
{
return this.split(char).length -1;
//return(this.length -this.replace(new RegExp(char, “g”).length));
}

To use this code, use something like this:

var main_string = “Hello world, this is pretty cool, don’t you think?”;
var number_of_e = main_string.count_occurrences(“e”);

This would return a value of ‘2’ because there are two letter ‘e’ in the main string. If you wanted to find the occurrences of a word, say, ‘hello’, then you would just put that in place of the ‘e’.

In python this is a little different. Here’s the code:

main_string = “Hello world, this is pretty cool, don’t you think?”
split_on_e = main_string.split(“e”)
number_or_e = len(split_on_e) – 1

The python version is a little more confusing, but it works the same and just as well as the javascript version.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s