Home > Uncategorized > Javascript Regular Expression - Greedy Vs Lazy - Quiz

Javascript Regular Expression - Greedy Vs Lazy - Quiz

February 4th, 2012

Take the following quiz for enhancing your understanding of the Regular Expression - Greedy Vs Lazy. You may like to ready the Javascript Regular Expression - Greedy Vs Lazy, before you take up this quiz.

Q1. Consider the following section of the code

var pattern = /^.*([\d]+)/;
var str = "Which year was known as great depression - 1929";
var newstr = str.replace(pattern, "$1");

what is the value of newstr

A. 1929
B. 9
C. Which year was known as great depression - 1929
D. 29

Q2. Consider the following section of code

var pattern = /^.*([\d]*)/;
var str = "Which year was known as great depression - 1929";

What is captured in the parenthesis

A. 1929
B. 9
C. Nothing
D. Which year was known as great depression - 1929

Try to do the above two questions yourself before you check the answers. The answers are at the end of this topic. You may also like to check

1. Javascript Tutorial for beginners

2. Regular Expression In Javascript on amazon

Answers and explanations
Q1. B
We are tempted to think that the parenthesis will capture 1929. However the .* keeps
matching anything including the digits. Finally to make the match successful the last
digit 9 is left to match to [\d]+. This is captured by the parenthesis.
Q2. C
Note that the our greed to attempt to capture 1929 gives a blank result. All the literals
are captured in .* and for the search to be successful, no match is required

Uncategorized

  1. No comments yet.
  1. No trackbacks yet.