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.
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