LearnFrenzy
Sign in Take a free test

String Methods · Predict the Output · Question 14

Swapping with capture groups Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

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

main.js
console.log("Sharma, Priya".replace(/(\w+), (\w+)/, "$2 $1"));
console.log("Sharma, Priya".replace(/(?<last>\w+), (?<first>\w+)/, "$<first> $<last>"));
  • A Priya Sharma Priya Sharma Correct
  • B $2 $1 $<first> $<last>
  • C Sharma Priya Sharma Priya
  • D Priya, Sharma Priya, Sharma
Correct Answer: Option A

Numbered groups ($1, $2) and named groups ($<name>) both insert the captured text in the replacement.

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