Post it to encourage everyone.
First read a piece of code,
<Script>
Var objReg =/^ [a-zA-Z] {1} (:) {1} $/gi;
Alert (objReg. test ("a:"); // return true
Alert (objReg. test ("a:"); // return false
</Script>
Why does the second test return false? Is it strange.
The reasons are as follows:
Test is actually the same as the exec method, but the return value is different. Test returns true or false (if exec does not return null), exec returns pattern (matching ).
While the exec execution process is: when the g parameter is included, the next matching will automatically jump to the location after lastIndex, that is, the 2nd location here. This location obviously does not match pattern. Therefore, false is returned.
Solution:
(1)
You can choose not to use g (Global parameter), that is-
<Script>
Var objReg =/^ [a-zA-Z] {1} (:) {1} $/I;
Alert (objReg. test ("a:"); // return true
Alert (objReg. test ("a:"); // return true
</Script>
(2)
You can use lastIndex = 0 to restore-
Var objReg =/^ [a-zA-Z] {1} (:) {1} $/gi;
Alert (objReg. test ("a:"); // return true
ObjReg. lastIndex = 0;
Alert (objReg. test ("a:"); // return true