-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Open
Labels
new-exampleA proposal of the new exampleA proposal of the new example
Description
const regexp = /[\uFF00-\uFFEF]/g
console.log(regexp.test(','))
console.log(regexp.test(','))
true
falseWhen you use a regex with these flags, the .test() method internally updates the lastIndex property of the RegExp object. The lastIndex is where the next search starts. After the first execution of .test(), the lastIndex is updated to the end of the last match. So, the next time .test() is invoked, it continues from the lastIndex.
In the code:
- The regular expression
/[\uFF00-\uFFEF]/gmatches Unicode characters in the range FF00 to FFEF. - With the first call
regexp.test(',')(where ',' is the Unicode character FF0C), it matches in this range, so the method returnstrue, and thelastIndexproperty of the regex is set to the end of the string. - On the second call
regexp.test(','), the search starts from the end of the string (as perlastIndex), so there isn't anything to match, hence it returnsfalseand resetslastIndexback to 0 for the next search.
Therefore, to continually get true from the .test() method, you have to reset the lastIndex manually every time after using the .test() method.
Here is a modification of the code that should work as intended:
const regexp = /[\uFF00-\uFFEF]/g;
console.log(regexp.test(',')); // output: true
regexp.lastIndex = 0; // reset lastIndex
console.log(regexp.test(',')); // output:Metadata
Metadata
Assignees
Labels
new-exampleA proposal of the new exampleA proposal of the new example