JavaScript Questions & Answers – Pattern Matching and Regular Expressions | JavaScript MCQs
Questions
1
The ‘$’ present in the RegExp object is called a ____________
Answer: metacharacter
2
Consider the following JavaScript statement containing regular expressions and check if the pattern matches?
var text = "testing: 1, 2, 3"; var pattern = /\d+/g;
Answer: pattern.test(text)
⭐ Make GKSeries Your Preferred Source on Google
Add GKSeries as Preferred Source
3
The regular expression to match any one character not between the brackets is __________
Answer: [^…]
4
What does /[^(]* regular expression indicate?
Answer: Match zero or more characters that are not open parenthesis
5
What will be the result when non greedy repetition is used on the pattern /a+?b/?
Answer: Matches the letter b preceded by the fewest number of a’s possible
6
What does the subexpression /java(script)?/ result in?
Answer: It matches “java” followed by the optional “script”
7
What is the most essential purpose of parentheses in regular expressions?
Answer: Define subpatterns within the complete pattern
8
The method that performs the search-and-replace operation to strings for pattern matching is _______
Answer: replace()
9
What would be the result of the following statement in JavaScript using regular expression methods?
Answer: Returns [“123″,”456″,”789”]
10
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);
}
Answer: Returns the same kind of array whether or not the regular expression has the global g flag
11
What will be the output of the following JavaScript code?
System.out.println(Pattern.matches("[amn]", "abcd"));
Answer: false
12
What will be the output of the following JavaScript code?
System.out.println(Pattern.matches("[amn]?", "a"));
Answer: true
13
What will be the output of the following JavaScript code?
System.out.println(Pattern.matches("\\d", "1"));
Answer: true
14
What will be the output of the following JavaScript code?
System.out.println(Pattern.matches("[adf]+", "a"));
Answer: true
15
What will be the output of the following JavaScript code?
System.out.println(Pattern.matches("[^abc]", "aemngq"));
Answer: false