The RegExp object in JavaScript is used for regular expression-related operations, and this object provides a method test to determine whether a string satisfies a pattern. The return value is True/false.
Today I came across a question:
<script type= "Text/javascript" > <!--var re =/^\d+ (?: \. \d)? $/ig; Alert (re.test (' 112.3 ')); Alert (re.test (' 33 ')); --> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Here the strings of both tests should match the pattern in the regular expression, and return true. But the test results are: true, false.
I estimate that the problem may be due to the fact that the RegExp object is stateful and that the state information is used in a step when the test method is executed, causing an error.
(Note: REGEXP Global objects have some static properties and methods, such as regexp.$1 ... REGEXP$9, etc.)
The solution to this problem is simply to reinitialize the regular expression object at a time:
<script type= "Text/javascript" > <!--alert (/^\d+ (?: \. \d)? $/ig.test (' 112.3 ')); Alert (/^\d+ (?: \. \d)? $/ig.test (' 33 ')); --> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
It seems to me that the behavior of JavaScript's regular expressions is very strange, and should be said to be a little bit different from normal usage habits. Although used for a long time JavaScript, but has not been aware of this strange phenomenon. Other languages such as Python, C # and so on are not like this.
For more information on the reasons for this problem, please feel free.
Of course, you used the global match mode G. So you need to reset the lastindex.
var re =/^\d+ (?: \. \d)? $/ig; ==> "IG"
Alert (re.test (' 112.3 '));
Re.lastindex=0//Add this sentence
Alert (re.test (' 33 '));
Or
var re =/^\d+ (?: \. \d)? $/i; ==> only "I", no G
Alert (re.test (' 112.3 '));
Alert (re.test (' 33 '));
That's OK.
For you this application environment, is not need "G", in fact "I" also do not,
Match a number to be case-sensitive??
Adding "I" or "G" will make your code slow.
It is recommended that ig be added only if necessary.