1

Count occurrences in a string

Function JavaScript 1 revisions 456 2 years ago 2 years ago
/** Function that count occurrences of a substring in a string;
 * @param {String} string               The string
 * @param {String} subString            The sub string to search for
 * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
 *
 * @author Vitim.us https://gist.github.com/victornpb/7736865
 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
 * @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
 */
function occurrences(string, subString, allowOverlapping) {
	string += '';
	subString += '';
	if (subString.length <= 0) return (string.length + 1);

	var n = 0,
		pos = 0,
		step = allowOverlapping ? 1 : subString.length;

	while (true) {
		pos = string.indexOf(subString, pos);
		if (pos >= 0) {
			++n;
			pos += step;
		} else break;
	}
	return n;
}

This function counts occurrences of a substring found in some other string, with support for overlapping.

occurrences('a', 'test');                  // 0
occurrences('test', 'test');               // 1
occurrences('test test', 'test');          // 2
occurrences('testestest', 'test', false);  // 2
occurrences('testestest', 'test', true);   // 3