Question Bank
JavaScript String-Only Regex Match: Three Approaches Quiz
Difficulty: Medium
Validate that a string contains only letters and whitespace, three ways (`String.prototype.match` + literal, `RegExp.test`, including-special-chars via `\D`), plus companions on Unicode letters and inverting the rule.
JavaScript String-Only Regex Match: Three Approaches Quiz
Validate that a string contains only letters and whitespace, three ways (`String.prototype.match` + literal, `RegExp.test`, including-special-chars via `\D`), plus companions on Unicode letters and inverting the rule.
510 views
4
Implement matchString(str) that returns true when str contains ONLY ASCII letters (a-z, A-Z) and whitespace; otherwise return false. Use String.prototype.match with the literal regex /^[A-Za-z\s]+$/.
Examples
Example 1:
Input: 'abc def'
Output: true
Explanation: Letters and a single space match the character class.Example 2:
Input: 'abc 123'
Output: false
Explanation: Digits are outside [A-Za-z\s].Implement matchString(str) again using a new RegExp(...) constructor + RegExp.prototype.test so the function returns the boolean directly. Why is test slightly faster than match for simple yes/no checks?
Examples
Example 1:
Input: 'abc def'
Output: true
Explanation: test returns boolean directly without allocating a match array.Implement matchStringIncludingSpecials(str) so it accepts letters, whitespace, AND special characters (!, +, punctuation) but still rejects digits. Use the \D (non-digit) character class. Explain the trade-off compared to whitelisting [A-Za-z\s].
Examples
Example 1:
Input: 'abc!+'
Output: true
Explanation: \D matches any non-digit character including punctuation.Example 2:
Input: 'abc 2!+'
Output: false
Explanation: contains a digit (2), so \D fails for that char.Implement matchUnicodeLetters(str) that accepts letters from ANY language (Cyrillic, Chinese, accented Latin) plus whitespace. Use the Unicode property escape \p{L} with the u flag.
Examples
Example 1:
Input: 'привет мир'
Output: true
Explanation: Cyrillic letters match \p{L}; the space matches \s.Example 2:
Input: 'naïve résumé'
Output: true
Explanation: accented Latin letters are still \p{L}.Example 3:
Input: 'abc1'
Output: false
Explanation: a digit is not a letter under the Unicode L category.Implement hasAnyDigit(str) returning true when the string contains at LEAST ONE digit. Contrast this with the anchored /^\D+$/ form: explain why one uses anchors and the other does not.
Examples
Example 1:
Input: 'abc def 12'
Output: true
Explanation: 1 and 2 are digits; finding one is enough.Example 2:
Input: 'abc def'
Output: false
Explanation: no digit anywhere in the string.