Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>/** 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 &lt;= 0) return (string.length + 1); var n = 0, pos = 0, step = allowOverlapping ? 1 : subString.length; while (true) { pos = string.indexOf(subString, pos); if (pos &gt;= 0) { ++n; pos += step; } else break; } return n; } </code></pre> <h2>Usage</h2> <pre><code>occurrences("foofoofoo", "bar"); //0 occurrences("foofoofoo", "foo"); //3 occurrences("foofoofoo", "foofoo"); //1 </code></pre> <h3>allowOverlapping</h3> <pre><code>occurrences("foofoofoo", "foofoo", true); //2 </code></pre> <p>Matches:</p> <pre><code> foofoofoo 1 `----´ 2 `----´ </code></pre> <h2>Unit Test</h2> <ul> <li><a href="https://jsfiddle.net/Victornpb/5axuh96u/" rel="noreferrer">https://jsfiddle.net/Victornpb/5axuh96u/</a></li> </ul> <h2>Benchmark</h2> <blockquote> <p>I've made a benchmark test and my function is more then 10 times faster then the regexp match function posted by gumbo. In my test string is 25 chars length. with 2 occurences of the character 'o'. I executed 1 000 000 times in Safari.</p> <p><strong>Safari 5.1</strong></p> <p>Benchmark> Total time execution: 5617 ms (regexp)</p> <p>Benchmark> Total time execution: 881 ms (my function 6.4x faster)</p> <p><strong>Firefox 4</strong></p> <p>Benchmark> Total time execution: 8547 ms (Rexexp)</p> <p>Benchmark> Total time execution: 634 ms (my function 13.5x faster)</p> <hr> <p>Edit: changes I've made</p> <ul> <li><p>cached substring length</p></li> <li><p>added type-casting to string.</p></li> <li><p>added optional 'allowOverlapping' parameter</p></li> <li><p>fixed correct output for "" empty substring case.</p></li> </ul> </blockquote> Gist <ul> <li><a href="https://gist.github.com/victornpb/7736865" rel="noreferrer">https://gist.github.com/victornpb/7736865</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload