JavaScript Regular Expressions

Regular expressions (RegEx) are patterns used to match character combinations in strings. They can be used for tasks like searching, replacing, and validating strings. Here’s a guide to using regular expressions in JavaScript:

Basic Syntax

Regular expressions in JavaScript can be created using either a literal notation or the `RegExp` constructor. The syntax for a regular expression literal is:


let regex = /pattern/flags;

                

For example:


let regex = /abc/i; // Matches 'abc' case-insensitively

                

Flags

Flags modify the behavior of the regular expression. Common flags include:

  • g - Global match (find all matches)
  • i - Case-insensitive match
  • m - Multi-line match
  • s - Dotall mode (matches newline characters)
  • u - Unicode; treat pattern as a sequence of Unicode code points
  • y - Sticky; matches only from the last index position

Methods

JavaScript strings and regular expressions have several useful methods:

  • test() - Tests if a pattern exists in a string
  • 
    let regex = /test/;
    console.log(regex.test('This is a test')); // true
    
                        
  • exec() - Executes a search for a match in a string and returns the result
  • 
    let regex = /test/;
    console.log(regex.exec('This is a test')); // ['test', index: 15, input: 'This is a test', groups: undefined]
    
                        
  • match() - Retrieves the matches of a string against a regular expression
  • 
    let str = 'This is a test';
    console.log(str.match(/test/)); // ['test']
    
                        
  • replace() - Replaces matches with a specified string
  • 
    let str = 'This is a test';
    console.log(str.replace(/test/, 'example')); // 'This is a example'
    
                        
  • split() - Splits a string into an array of substrings based on a regular expression
  • 
    let str = 'one,two,three';
    console.log(str.split(/,/)); // ['one', 'two', 'three']