Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

What will be the purpose of exec() in the following JavaScript code?
var pattern = /Java/g;
var text = “JavaScript is more fun than Java!”;
var result;
while ((result = pattern.exec(text)) != null)
{
alert(“Matched ‘” + result[0] + “‘” +” at position ” + result.index +”; next search begins at ” + pattern.lastIndex);
}

What will be the purpose of exec() in the following JavaScript code?
var pattern = /Java/g;
var text = “JavaScript is more fun than Java!”;
var result;
while ((result = pattern.exec(text)) != null)
{
alert(“Matched ‘” + result[0] + “‘” +” at position ” + result.index +”; next search begins at ” + pattern.lastIndex);
}
a) Returns the same kind of array whether or not the regular expression has the global g flag
b) Returns different arrays in the different turns of iterations
c) Return a sub part of the array
d) Returns a null value

Answer: a
Explanation: exec() returns the same kind of array whether or not the regular expression has the global g flag. Recall that match() returns an array of matches when passed a global regular expression. exec(), by contrast, always returns a single match and provides complete information about that match. When exec() is called on a regular expression that has the g flag, it sets the lastIndex property of the regular expression object to the character position immediately following the matched substring. When exec() is invoked a second time for the same regular expression, it begins its search at the character position indicated by the lastIndex property. If exec() does not find a match, it resets lastIndex to 0.

Join The Discussion