Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging the RegExp flags
    primarykey
    data
    text
    <p>So basically I wrote myself this function so as to be able to count the number of occurances of a Substring in a String:</p> <pre><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) { // needle.global = true; return this.match(needle).length; } return 0; }; </code></pre> <p>The method itself performs rather well and both the RegExp and String based searches are quite comparable as to the execution time (both ~2ms on the entire vast Ray Bradbury's "451 Fahrenheit" searching for all the "the"s).</p> <p>What sort of bothers me, though, is the impossibility of changing the flag of the supplied RegExp instance. There is no point in calling <em>String.prototype.match</em> in this function without the global flag of the supplied Regular Expression set to true, as it would only note the first occurance then. You could certainly set the flag manually on each RegExp passed to the function, I'd however prefer being able to clone and then manipulate the supplied Regular Expression's flags.</p> <p>Astonishingly enough, I'm not permitted to do so as the <em>RegExp.prototype.global</em> flag (more precisely all flags) appear to be read-only. Thence the commented-out line 8. </p> <p>So my question is: <strong>Is there a <em>nice</em> way of changing the flags of a RegExp object?</strong></p> <p>I don't really wanna do stuff like this:</p> <pre><code>if(!expression.global) expression = eval(expression.toString() + "g"); </code></pre> <p>Some implementations might not event support the <em>RegExp.prototype.toString</em> and simply inherit it from the <em>Object.prototype</em>, or it could be a different formatting entirely. And it just seems as a bad coding practice to begin with.</p>
    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.
 

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