javascript| objects
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>
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>
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.
Posted on 2007-01-08 15:23 Wood Wild Fox Reading (330) Comments (1) Edit Favorites Reference Net pick categories: asp,js,css
Feedback
# Re: note the test method for RegExp objects in JavaScript 2007-01-08 23:33 Derek.
Lastindex Property-Also
RegExp Object Properties | Regular Expression Syntax
Applies to:regexp Object
Requirements
Version 3
Returns the character position where the next match begins in a searched string.
Regexp.lastindex
The object associated the to always the global RegExp object.
Remarks
The Lastindex property is zero-based, which is, the index of the the the the "the" is zero. Its initial value is–1. Its value is modified whenever a successful the match is made.
The Lastindex property is modified by the Exec and test methods the RegExp object, and the match, replace, and split me Thods of the String object.
The following rules apply to values of lastindex:
If There is no match, lastindex is set to-1.
If Lastindex is greater than the length of the string, test and exec fail and lastindex are set to-1.
If lastindex is equal to the length of the string, the regular expression matches if the pattern matches the empty string. Otherwise, the match fails and lastindex is reset to-1.
Otherwise, lastindex is set to the next position following the most match.