Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>tl;dr: Generic Pattern Counter</strong></p> <pre><code>// THIS IS WHAT YOU NEED const count = (str) =&gt; { const re = /YOUR_PATTERN_HERE/g return ((str || '').match(re) || []).length } </code></pre> <p>For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/* * Example */ const count = (str) =&gt; { const re = /[a-z]{3}/g return ((str || '').match(re) || []).length } const str1 = 'abc, def, ghi' const str2 = 'ABC, DEF, GHI' console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`) console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)</code></pre> </div> </div> </p> <p><strong>Original Answer</strong></p> <p>The problem with your initial code is that you are missing the <a href="http://www.javascriptkit.com/jsref/regexp.shtml" rel="noreferrer">global identifier</a>:</p> <pre><code>&gt;&gt;&gt; 'hi there how are you'.match(/\s/g).length; 4 </code></pre> <p>Without the <code>g</code> part of the regex it will only match the first occurrence and stop there.</p> <p>Also note that your regex will count successive spaces twice:</p> <pre><code>&gt;&gt;&gt; 'hi there'.match(/\s/g).length; 2 </code></pre> <p>If that is not desirable, you could do this:</p> <pre><code>&gt;&gt;&gt; 'hi there'.match(/\s+/g).length; 1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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