Regular expressions (regex) describe patterns in text. JavaScript provides the RegExp object and methods on strings for searching, matching, and replacing.

Creating a RegExp

  // Literal syntax
let pattern1 = /hello/i; // i = case insensitive

// Constructor (useful for dynamic patterns)
let pattern2 = new RegExp('hello', 'i');
  

Flags

Flag Meaning
g Global — find all matches
i Case insensitive
m Multiline
s Dot matches newline
u Unicode
y Sticky

String Methods

  let text = 'Hello world, hello JavaScript';

text.match(/hello/gi);     // ['Hello', 'hello']
text.search(/world/);      // 6 (index of first match)
text.replace(/hello/gi, 'Hi'); // 'Hi world, Hi JavaScript'
text.split(/,\s*/);        // ['Hello world', 'hello JavaScript']
  

RegExp Methods

  let regex = /(\d{4})-(\d{2})-(\d{2})/;
let date = '2024-06-13';

regex.test(date);           // true
regex.exec(date);
// ['2024-06-13', '2024', '06', '13', index: 0, ...]
  

Common Patterns

  /^\d+$/           // digits only
/^[a-zA-Z]+$/     // letters only
/^[\w.-]+@[\w.-]+\.\w+$/  // simple email (not production-grade)
/^(https?):\/\//  // http or https URL start
/\s+/             // one or more whitespace
/\d{3}-\d{4}/     // phone pattern like 123-4567
  

Character Classes

  /[abc]/     // a, b, or c
/[^abc]/    // NOT a, b, or c
/[a-z]/     // lowercase letter
/[0-9]/     // digit
/\w/        // word character [a-zA-Z0-9_]
/\d/        // digit
\s          // whitespace
.           // any character (except newline unless s flag)
  

Quantifiers

  /a*/   // 0 or more
/a+/   // 1 or more
/a?/   // 0 or 1
/a{3}/ // exactly 3
/a{2,5}/ // 2 to 5
  

Groups and Capturing

  let re = /(\w+)@(\w+)\.(\w+)/;
let match = '[email protected]'.match(re);
console.log(match[1]); // 'user'
console.log(match[2]); // 'mail'
console.log(match[3]); // 'com'
  

Named Groups (ES2018)

  let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
let { groups } = re.exec('2024-06-13');
console.log(groups.year);  // '2024'
console.log(groups.month); // '06'
  

Practical Example: Validation

  function isValidPassword(password) {
    // At least 8 chars, one letter, one digit
    return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(password);
}

console.log(isValidPassword('abc12345')); // true
console.log(isValidPassword('short'));  // false
  

Regular expressions are powerful for validation, parsing, and text processing — use them carefully and test edge cases.