LearnFrenzy
Sign in Take a free test

String Methods · String Methods MCQ · Question 14

test() with a global regex Answer, explanation & discussion

  • MCQ
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

Why can const re = /\d/g; make re.test("a1") return true and then false on the next call with the same string?

  • A A global regex stores lastIndex and continues searching from there on the next call Correct
  • B test() caches its result
  • C Strings change after testing
  • D Digits can only be matched once per program
Correct Answer: Option A

After the first match lastIndex is 2, so the second call searches from index 2, finds nothing and resets lastIndex to 0. Do not use g for simple yes/no tests.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links