Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, your current code does not work correctly when <code>needle</code> is a regex which does not match. i.e. The following line:</p> <pre class="lang-js prettyprint-override"><code>return this.match(needle).length; </code></pre> <p>The <code>match</code> method returns <code>null</code> when there is no match. A JavaScript error is then generated when the <code>length</code> property of <code>null</code> is (unsuccessfully) accessed. This is easily fixed like so:</p> <pre class="lang-js prettyprint-override"><code>var m = this.match(needle); return m ? m.length : 0; </code></pre> <p>Now to the problem at hand. You are correct when you say that <code>global</code>, <code>ignoreCase</code> and <code>multiline</code> are read only properties. The only option is to create a new RegExp. This is easily done since the regex source string is stored in the <code>re.source</code> property. Here is a tested modified version of your function which corrects the problem above and creates a new RegExp object when <code>needle</code> does not already have its <code>global</code> flag set:</p> <pre class="lang-js prettyprint-override"><code>String.prototype.numberOf = function(needle) { var num = 0, lastIndex = 0; if (typeof needle === "string" || needle instanceof String) { while((lastIndex = this.indexOf(needle, lastIndex) + 1) &gt; 0) {num++;} return num; } else if(needle instanceof RegExp) { if (!needle.global) { // If global flag not set, create new one. var flags = "g"; if (needle.ignoreCase) flags += "i"; if (needle.multiline) flags += "m"; needle = RegExp(needle.source, flags); } var m = this.match(needle); return m ? m.length : 0; } return 0; }; </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