InterviewHubPRO
Section Overview
Q162

Question 162 of 521

Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)

31%
JavaScript Internals (521 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)

What are regular expression patterns

Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,

  1. Brackets: These are used to find a range of characters. For example, below are some use cases,
    1. [abc]: Used to find any of the characters between the brackets(a,b,c)
    2. [0-9]: Used to find any of the digits between the brackets
    3. (a|b): Used to find any of the alternatives separated with |
  2. Metacharacters: These are characters with a special meaning. For example, below are some use cases,
    1. \d: Used to find a digit
    2. \s: Used to find a whitespace character
    3. \b: Used to find a match at the beginning or ending of a word
  3. Quantifiers: These are useful to define quantities. For example, below are some use cases,
    1. n+: Used to find matches for any string that contains at least one n
    2. n*: Used to find matches for any string that contains zero or more occurrences of n
    3. n?: Used to find matches for any string that contains zero or one occurrences of n

Practical Code Example

javascript
// Common Regular Expression Patterns:
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const digitsOnly = /^\d+$/;
const phonePattern = /^\(\d{3}\)\s\d{3}-\d{4}$/;

console.log(emailPattern.test('dev@example.com')); // true
console.log(digitsOnly.test('12345a'));            // false