LearnFrenzy
Sign in Take a free test

String Methods · Predict the Output · Question 17

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

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
const re = /cat/g;
console.log(re.test("cat"), re.test("cat"), re.test("cat"));
  • A true true true
  • B true false true Correct
  • C true false false
  • D false true false
Correct Answer: Option B

After the first match lastIndex is 3, so the second call finds nothing (and resets lastIndex to 0); the third call matches again.

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