The RegExp object in JavaScript is used for regular expression-related operations. This object provides a method test to determine whether a certain string satisfies a certain pattern. The return value is true/false.
I encountered a problem today:
]
The two test strings here should both satisfy the pattern in the regular expression and return true. However, the test results are: true, false.
I guess the cause of the problem may be Because the RegExp object is stateful, and the state information will be used in a certain step during the execution of the test method, this causes an error.
(Note: The RegExp global object has some static properties and methods, such as RegExp.$1...RegExp$9, etc.)
The solution to this problem is also very simple, which is to re-initialize the regular expression each time Expression object:
If you need to introduce external Js, you need Refresh to execute
]
In my opinion, the behavior of regular expressions in JavaScript is very strange. It should be said that it is a little different from normal usage habits. Although I have been using JavaScript for a long time, I have never noticed this strange phenomenon. Other languages such as Python, C#, etc. are not like this.
Friends who know the detailed reasons for this problem, please feel free to give me some advice.
Of course, you used the global matching mode g. So you need to reset lastIndex after use
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'));
This is OK
For your application environment, it is not necessary "g " , in fact, "i" is not required either.
Is matching a number case-sensitive? ?
Whether adding "i" or "g" will make your code slower. It is recommended to add ig only when absolutely necessary