Occurrences of Substring in String

Get the number of occurrences of a substring in a string.

Method 1

// In my opinon this is the best way to do it
function substr_count(str, subStr)
    str.split(subStr).length - 1;
}

Method 2

// this method uses a loop
function substr_count(haystack, needle) {
	if (haystack=="" || needle=="") { return false; }
	if (haystack == null || needle == null) { return false; }
	
	pos = num = 0;
	haystack = haystack.toLowerCase();
	needle = needle.toLowerCase();
	
	do {
		pos = haystack.indexOf(needle, pos);
		if (pos > -1) {
			num++;
			pos += needle.length;
		} else {
			return (num);
		}
	} while (true);
}

Method 3

// this method uses regex
function substr_count(haystack, needle) {
  var regExp = new RegExp(needle, "gi");
  return (haystack.match(regExp) || []).length;
}

Example:

Given the following sentence as the input string:

var string = "With indoor climbing you will get both aerobic and anaerobic exercise engaging and working all muscle groups simultaneously. As an exercise, you really can’t do better than climbing. Indoor climbing will improve all aspects of your physical condition. You will see improvement in your balance, flexibility, and agility and develop both upper and lower body strength. Best of all, you will burn calories at a higher rate than most strenuous workouts and will do it before you know it.";

var countNumberOf = "it";

count = substr_count(string, countNumberOf); // count == 6;

Here are the six ...

With indoor climbing you will get both aerobic and anaerobic exercise engaging and working all muscle groups simultaneously. As an exercise, you really can’t do better than climbing. Indoor climbing will improve all aspects of your physical condition. You will see improvement in your balance, flexibility, and agility and develop both upper and lower body strength. Best of all, you will burn calories at a higher rate than most strenuous workouts and will do it before you know it.

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use