Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Regex Javascript //g flag affecting state?
    primarykey
    data
    text
    <p>I had <a href="https://stackoverflow.com/questions/9860057/javascript-regex-match-defective">another question</a> and although it was answered i dont understand WHY the regex is affected the way it is</p> <p>From <a href="http://www.w3schools.com/jsref/jsref_obj_regexp.asp" rel="nofollow noreferrer">w3schools</a> it says</p> <blockquote> <p>g: Perform a global match (find all matches rather than stopping after the first match)</p> </blockquote> <p>Ok sure. I understand. Thats why i get an array in this code</p> <pre><code>var str="The rain in SPAIN stays mainly in the plain"; var patt1=/ain/gi; document.write(str.match(patt1)); </code></pre> <p>Output:</p> <pre><code>ain,AIN,ain,ain </code></pre> <p>Regex is similar, with <code>/g</code> it will replace more than one instance.</p> <p>However in match</p> <pre><code>var re=/hi/gi; alert(re.test("hi") + " " + re.test("hi")); </code></pre> <p>The result is "true false".</p> <p>Now why the $%^&amp; does it do that? The string in both test are exactly the same! In the past i thought global meant it will search across newlines (which is what i wanted to do in this test). The very first thing i quoted was about g being a global match.</p> <p>Nothing makes any reference about it affecting the NEXT CALL! without /g the code will work correctly (also i dont need to go across newlines). WHY is it affecting the next test? gumbo answer makes mention it affects the lastIndex across calls and what the %^&amp;* i had no idea there is shared state as the other two functions made no use of it while i used the g flag. I only wanted a true and false but if anything shouldnt match return an int containing the amount of matches it found globally? (ie 1 in "hi" but 2 in the string "hihi").</p> <p>Why the heck is g affecting my next call when doing regex.test?! Also if you can, provide when i'd actually want that 'feature'</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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