JavaScript RegExp

What Are Regular Expressions?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, they are implemented using the RegExp object or regular expression literals.

Syntax

Regular Expression Literal:

const regex = /pattern/flags;

Using the RegExp Constructor:

const regex = new RegExp('pattern', 'flags');

Flags in Regular Expressions

Flags are optional modifiers that enhance the functionality of a regular expression.

FlagDescriptionExample
gGlobal search (find all matches)./pattern/g
iCase-insensitive search./pattern/i
mMultiline search./pattern/m
sAllows the dot . to match newline characters./pattern/s
uEnables full Unicode support./pattern/u
ySticky search (matches from the last index)./pattern/y

Regular Expression Syntax

A regular expression consists of:

Literals: Match exact characters.

const regex = /hello/;
console.log(regex.test('hello world')); // true

Special Characters: Match patterns based on rules.

  • . : Matches any character except newline.
  • \d: Matches any digit (0-9).
  • \w: Matches alphanumeric characters and underscore.
  • \s: Matches whitespace.
  • ^: Matches the beginning of a string.
  • $: Matches the end of a string.
  • [ ]: Matches any character inside the brackets.
  • { }: Specifies repetition.
  • |: Acts as an OR operator.

Common Regular Expression Examples

1. Testing Strings

The test() method checks if a pattern exists in a string.

const regex = /hello/;
console.log(regex.test('hello world')); // true
console.log(regex.test('hi there')); // false

2. Extracting Matches

The match() method extracts matched patterns.

const regex = /\d+/g; // Matches one or more digits
const result = 'The year is 2024'.match(regex);
console.log(result); // ['2024']

3. Replacing Text

The replace() method replaces matched patterns with new text.

const regex = /cat/gi;
const result = 'Cat and dog are friends. cat plays a lot.'.replace(regex, 'dog');
console.log(result); // "dog and dog are friends. dog plays a lot."

4. Splitting Strings

The split() method splits a string based on a pattern.

const regex = /\s+/; // Matches spaces
const result = 'Hello world, JavaScript is awesome!'.split(regex);
console.log(result); // ['Hello', 'world,', 'JavaScript', 'is', 'awesome!']

Advanced Regular Expressions

1. Using Groups

Parentheses ( ) are used to group patterns and extract matched groups.

const regex = /(\d{4})-(\d{2})-(\d{2})/;
const result = '2024-11-25'.match(regex);
console.log(result[0]); // Full match: 2024-11-25
console.log(result[1]); // Group 1: 2024
console.log(result[2]); // Group 2: 11
console.log(result[3]); // Group 3: 25

2. Lookaheads and Lookbehinds

  • Positive Lookahead ((?=…)): Ensures that a pattern is followed by another pattern.
  • Negative Lookahead ((?!…)): Ensures that a pattern is NOT followed by another pattern.
  • Positive Lookbehind ((?<=…)): Ensures that a pattern is preceded by another pattern.
  • Negative Lookbehind ((?<!…)): Ensures that a pattern is NOT preceded by another pattern.

Example:

const regex = /(?<=\$)\d+/;
const result = '$1234'.match(regex);
console.log(result[0]); // 1234

Validating Input with Regular Expressions

Example: Email Validation

const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(regex.test('example@email.com')); // true
console.log(regex.test('invalid-email')); // false

Example: Password Validation

const regex = /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(regex.test('Passw0rd@')); // true
console.log(regex.test('password')); // false

Common Mistakes and Tips

Escaping Special Characters: Always escape special characters like . or * if you want to match them literally.

const regex = /\./; // Matches a literal dot
console.log(regex.test('www.example.com')); // true

Avoid Overcomplication: Use regex only when necessary. Complex patterns can make code harder to maintain.

Practice with Tools: Use tools like regex101.com to test and debug your expressions.

Practical Applications

  1. Form Validation: Validate inputs like emails, phone numbers, and passwords.
  2. Data Parsing: Extract specific information from large text files or logs.
  3. Text Manipulation: Find and replace patterns in strings for data cleaning.

Leave a Comment