Debug fifteen programs that use string methods and regular expressions: invalid regex literals, replaceAll and matchAll without g, RegExp built from user input, null match results, string methods on numbers and undefined, and silent bugs from replace, case-sensitive searches, unescaped patterns, default sorting and inner spaces.
Question 11Easy
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
main.js
const find = "1+1"; // text the user wants to replace
const text = "Answer: 1+1=2";
console.log(text.replace(new RegExp(find), "two"));
AIn a regex, + means "one or more", so the pattern looks for "11" – escape the input or use text.replace(find, "two")
Breplace cannot take a RegExp object
CThe = sign stops the search
DRegExp needs the g flag to match anything
Correct Answer: Option A
The pattern 1+1 matches one or more 1s followed by 1 (e.g. "11"), which does not occur. A plain string pattern (or an escaped one) replaces "1+1" literally: "Answer: two=2".
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·