What will be the Output of following javascript ?
<script language=“javascript”> javascript:function x ( ) { var qpt = “First come, first served”; var pattern = /first/g; document.write(qpt.match(pattern) [ 1 ]); } x ( ) ; </script>- AOption (a)
first
- BOption (b)
First
- COption (c)
undefined
- DOption (d)
None of the above
View answer & explanationHide answer & explanation
Correct answer
undefined
Why this answer is correct
The correct answer is : option 3
Key Points
In JavaScript, the String.prototype.match() method is used to retrieve the result of matching a string against a regular expression.
If the regular expression has the g flag, it returns an array of all matches.
Code:
<script language="javascript"> function x() { var qpt = "First come, first served"; var pattern = /first/g; document.write(qpt.match(pattern)[1]); } x(); </script>Step-by-Step Explanation:
- qpt = "First come, first served"
- pattern = /first/g → case-sensitive match for "first"
- qpt.match(pattern) will return: ["first"]
- match()[1] tries to access the second element (index 1) of the result array.
- But only one match ("first") is found → match() returns an array with 1 element.
- match()[1] → undefined
Important Note: The pattern does not match "First" because regular expressions are case-sensitive by default.
Final Output: undefined
Correct Answer: Option 3) undefined ✅