Home ยป JavaScript Regular Expressions: A Comprehensive Tutorial

JavaScript Regular Expressions: A Comprehensive Tutorial

Regular expressions, often abbreviated as regex or regexp, are patterns used to match character combinations in strings. They are incredibly powerful for validating, searching, and manipulating text.

JavaScript provides a built-in RegExp object to work with regular expressions.

This tutorial will guide you through creating and using regular expressions in JavaScript with various examples.

1. Creating Regular Expressions

There are two ways to create a regular expression in JavaScript:

Literal notation: Enclosed between slashes (/pattern/flags).
Constructor function: Using new RegExp(‘pattern', ‘flags').

Example 1: Creating a Regular Expression

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

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

console.log(regex1.test('hello world')); // Output: true
console.log(regex2.test('hello world')); // Output: true

2. Common Regular Expression Flags

Flags are optional parameters that can change how the pattern is matched:

g: Global search (find all matches).
i: Case-insensitive search.
m: Multi-line search.
s: Allows . to match newline characters.
u: Enables full Unicode support.
y: “Sticky” search, matches only from the current position in the string.

Example 2: Using Flags

const regex = /hello/i; // Case-insensitive
console.log(regex.test('Hello world')); // Output: true

3. Testing Strings with test()

The test() method checks if a pattern exists in a string. It returns true or false.

Example 3: Testing for Matches

const regex = /cat/;
console.log(regex.test('The cat is here.')); // Output: true
console.log(regex.test('The dog is here.')); // Output: false

4. Finding Matches with match()

The match() method returns an array of all matches or null if no match is found.

Example 4: Finding All Matches

const text = 'The rain in Spain falls mainly in the plain.';
const regex = /in/g; // Global search for 'in'

const matches = text.match(regex);
console.log(matches); // Output: ['in', 'in', 'in']

5. Replacing Text with replace()

The replace() method searches a string for a match and returns a new string with the replacement.

Example 5: Simple Replacement

const text = 'Hello, World!';
const result = text.replace(/World/, 'JavaScript');
console.log(result); // Output: 'Hello, JavaScript!'

Example 6: Global Replacement

const text = 'The quick brown fox jumps over the lazy dog.';
const result = text.replace(/o/g, '0'); // Replace all 'o' with '0'
console.log(result); // Output: 'The quick br0wn f0x jumps 0ver the lazy d0g.'

6. Extracting Parts of a String with exec()

The exec() method searches for a match in a string and returns an array of information or null.

Example 7: Using exec()

const regex = /(\d{4})-(\d{2})-(\d{2})/; // Pattern for a date (YYYY-MM-DD)
const text = 'Today's date is 2024-10-06.';
const match = regex.exec(text);

console.log(match[0]); // Output: '2024-10-06'
console.log(match[1]); // Output: '2024' (First capturing group)
console.log(match[2]); // Output: '10' (Second capturing group)
console.log(match[3]); // Output: '06' (Third capturing group)

7. Regular Expression Patterns

1. Character Classes

.: Matches any character except newline.
\d: Matches any digit (equivalent to [0-9]).
\D: Matches any non-digit.
\w: Matches any word character (alphanumeric + underscore).
\W: Matches any non-word character.
\s: Matches any whitespace character (spaces, tabs, line breaks).
\S: Matches any non-whitespace character.

Example 8: Using Character Classes

const regex = /\d+/; // Matches one or more digits
console.log(regex.test('Year 2024')); // Output: true

2. Anchors

^: Matches the beginning of a string.
$: Matches the end of a string.

Example 9: Using Anchors

const regex = /^Hello/; // Matches 'Hello' at the beginning
console.log(regex.test('Hello, World!')); // Output: true
console.log(regex.test('Say Hello!'));    // Output: false

3. Quantifiers

*: Matches 0 or more occurrences.
+: Matches 1 or more occurrences.
?: Matches 0 or 1 occurrence.
{n}: Matches exactly n occurrences.
{n,}: Matches n or more occurrences.
{n,m}: Matches between n and m occurrences.

Example 10: Using Quantifiers

const regex = /go{2,4}gle/; // Matches 'google', 'gooogle', 'goooogle'
console.log(regex.test('google'));   // Output: true
console.log(regex.test('gooogle'));  // Output: true
console.log(regex.test('googl'));    // Output: false

4. Groups and Ranges

[abc]: Matches any one of the characters inside the brackets (e.g., a, b, or c).
[a-z]: Matches any character in the specified range (e.g., any lowercase letter).
(abc): Capturing group for the characters within.
(?:abc): Non-capturing group.

Example 11: Using Groups and Ranges

const regex = /[A-Z]{3}-\d{4}/; // Matches patterns like 'ABC-1234'
console.log(regex.test('ABC-1234')); // Output: true
console.log(regex.test('abc-1234')); // Output: false

8. Escape Characters

In regex, special characters (e.g., . * + ? ( ) [ ] \ { } | ^ $) need to be escaped with a backslash (\) if you want to match them literally.

Example 12: Escaping Special Characters

const regex = /\.\*/; // Matches the literal characters '.*'
console.log(regex.test('Hello .* World')); // Output: true

9. Lookaheads and Lookbehinds

Lookahead ((?=…)): Asserts that a given pattern must be followed by another pattern.
Negative Lookahead ((?!…)): Asserts that a given pattern must NOT be followed by another pattern.
Lookbehind ((?<=…)): Asserts that a given pattern must be preceded by another pattern.
Negative Lookbehind ((?<!…)): Asserts that a given pattern must NOT be preceded by another pattern.

Example 13: Using Lookaheads

const regex = /\d+(?= dollars)/; // Matches digits followed by 'dollars'
console.log(regex.exec('The price is 100 dollars')); // Output: ['100']

Conclusion

JavaScript regular expressions are a powerful tool for pattern matching and text manipulation. By understanding the different patterns, flags, and methods (test, match, replace, exec), you can create complex searches and validations in your code.

The examples in this tutorial cover the basics and some advanced use cases to help you get started with regex in JavaScript.

Feel free to experiment with different patterns and methods to enhance your text-processing capabilities!

You may also like