JavaScript : Regular Expressions

Regular expressions, often abbreviated as regex or regexp, are patterns used to match character combinations in strings. They are powerful tools for string manipulation and searching. In JavaScript, regular expressions are objects that can be used with methods like test() , match() , search() , replace() , and split() to perform various operations on strings. Here's an overview of regular expressions in JavaScript:

1. Creating Regular Expressions:


You can create a regular expression by enclosing a pattern within forward slashes /pattern/ . Additionally, you can use the RegExp constructor.


// Using literal notation
const regex1 = /pattern/;

// Using RegExp constructor
const regex2 = new RegExp('pattern');

 

2. Basic Patterns:

 

  • Characters: Ordinary characters match themselves in the string.
  • Metacharacters: Special characters like  , , , , , ,  , , ,  , , }, , and  ) have special meanings.
  • Character Classes: [...] matches any single character within the brackets.
  • Quantifiers: * , , ,  {n} , {n,} , {n,m} specify the number of occurrences of the preceding element.

3. Using Regular Expressions:

 

  • test(string) : Tests if the regex pattern matches the string and returns true or false .
  • exec(string) : Executes a search for a match in the string and returns an array of information or null if no match is found.
  • match(regex) : Returns an array containing all matches of the regex pattern in the string.
  • search(regex) : Searches for a match in the string and returns the index of the first match or -1 if not found.
  • replace(regex, replacement) : Replaces matches of the regex pattern with the specified replacement string.
  • split(regex) : Splits the string into an array of substrings using the regex pattern as a delimiter.

Example:


const str = 'The quick brown fox jumps over the lazy dog';

const regex = /fox/;

console.log(regex.test(str));     // Output: true
console.log(str.match(regex));    // Output: ['fox']
console.log(str.search(regex));   // Output: 16
console.log(str.replace(regex, 'cat')); // Output: 'The quick brown cat jumps over the lazy dog'
console.log(str.split(regex));    // Output: ['The quick brown ', ' jumps over the lazy dog']

 

Flags:


Regular expressions can also have flags that modify their behavior, such as i (case-insensitive), g (global match), and m (multiline match). Flags are appended after the closing slash.


const regex = /pattern/ig;
 

Regular expressions are versatile and powerful tools for string manipulation and searching. However, they can be complex and difficult to understand, so it's important to practice and refer to documentation when working with them.