On the problem of regular matching

description: a regular match is given to the content of an input box, and the matching content is the product activation code.
looks like this: "0C31-0B81-BB32-3094-0C31-0B81-BB32-3094"

Code:

$("-sharplicenseCode").keyup(function () {
        let licenseCode = $(this).val();
        let reg = /^([A-Z0-9]{4}-){7}[A-Z0-9]{4}$/g;
        console.log(reg.test(licenseCode));
        console.log(reg.test(licenseCode));
        console.log(reg.test(licenseCode));
        console.log(reg.test(licenseCode));
        if (reg.test(licenseCode)) {
            checkBtn.removeAttr("disabled");
            console.log(11);
        } else {
            checkBtn.attr("disabled", "disabled");
            console.log(22);
        }
    });
The result of

input surprised me!

clipboard.png

true,false,true,false

console.log();


:

clipboard.png

I can"t figure it out! Why?


because of / g

reg = /1/g
s = '1'
reg.test(s) // true
reg.test(s) // false
reg = /1/
reg.test(s) // true
reg.test(s) // true

use test () when setting global flag regular
if the regular expression sets the global flag, the execution of, test () will change the regular expression lastIndex property. Execute the test () method continuously, and the subsequent execution will start at lastIndex to match the string, (exec () and also change the lastIndex attribute value of the rule itself.

refer to https://developer.mozilla.org.

Menu