Q. Consider the following statements.
In order to check if the pattern matches with the string “t”, the statement is
Code:
var t= "Example: 4, 5, 6"; // text var p = /\d+/g // Matches all instances of one or more digits
✅ Correct Answer: (A)
p.test(t)
Explanation:
- p.test(t) is the correct method to check if a regular expression (p) matches the string (t).
- In this case, p is the regular expression /\d+/g, which matches one or more digits, and t is the string "Example: 4, 5, 6".
- The test() method is used with regular expressions to check if the pattern matches any part of the string. It returns true if the pattern is found, and false otherwise.
Example:
var t = "Example: 4, 5, 6"; // text
var p = /\d+/g; // Matches one or more digits
console.log(p.test(t)); // true, because digits 4, 5, and 6 are found in the string
Why the other options are incorrect:
- (B) t.test(p): This is incorrect because test() is a method of regular expression objects, not strings.
- (C) t.equals(p): This is incorrect because there is no equals() method for strings in JavaScript to compare a string and a regular expression.
- (D) t == p: This is incorrect because == is used for comparison, but it doesn't check if a regular expression matches a string.
So, the correct answer is (A) p.test(t).