Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test() + regex with fullwidth comma #322

Open
endenwer opened this issue Dec 20, 2023 · 0 comments
Open

test() + regex with fullwidth comma #322

endenwer opened this issue Dec 20, 2023 · 0 comments
Labels
new-example A proposal of the new example

Comments

@endenwer
Copy link

const regexp = /[\uFF00-\uFFEF]/g
console.log(regexp.test(','))
console.log(regexp.test(','))
true
false

When 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:

  1. The regular expression /[\uFF00-\uFFEF]/g matches Unicode characters in the range FF00 to FFEF.
  2. With the first call regexp.test(',') (where ',' is the Unicode character FF0C), it matches in this range, so the method returns true, and the lastIndex property of the regex is set to the end of the string.
  3. On the second call regexp.test(','), the search starts from the end of the string (as per lastIndex), so there isn't anything to match, hence it returns false and resets lastIndex back 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:
@endenwer endenwer added the new-example A proposal of the new example label Dec 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new-example A proposal of the new example
Projects
None yet
Development

No branches or pull requests

1 participant