Regular Expressions

Creating Regular Expressions:

You can create a regular expression using the RegExp constructor or a literal syntax enclosed in slashes (/pattern/).

Using RegExp constructor:

                                      
                                        const regex = new RegExp('pattern');
                                      
                                    

Literal Syntax:

                                      
                                        const regexLiteral = /pattern/;
                                      
                                    

Basic Patterns:

Characters:

A regular expression can consist of literal characters, such as /abc/ to match the sequence "abc."

Quantifiers:

Quantifiers specify how many occurrences of a character or group are expected.

Examples:

  • *: Zero or more occurrences
  • +: One or more occurrences
  • ?: Zero or one occurrence
  • {n}: Exactly n occurrences
  • {n,}: n or more occurrences
  • {n,m}: Between n and m occurrences

Character Classes:

Character classes allow you to match any one of a set of characters.

Square Brackets:

  • [abc]: Matches any one of the characters a, b, or c.
  • [^abc]: Matches any character except a, b, or c.
Anchors:

Anchors are used to match positions in the string rather than characters.

  • ^: Matches the start of a string.
  • $: Matches the end of a string.
Modifiers:

i (case-insensitive):

  • /pattern/i makes the pattern case-insensitive.
Metacharacters:

\ (backslash):

  • Escapes a metacharacter, treating it as a literal character.

Example Usage:

                                          
                                            const text = "Hello, this is a sample text with some patterns.";
const pattern = /pattern/;

console.log(pattern.test(text));  // Output: true
console.log(text.match(pattern)); // Output: ['pattern']                                            
                                          
                                        

Test Regular Expressions Online:

You can test and experiment with regular expressions using online tools like RegExr or Regex101.

Hey there! Let's go for Learn fasta then! It is more than just coding; it is to have the superpower that can solve any problem. Through simple and easy-to-grasp examples you will sail through the learning process. In addition, it is not just about coding– you will acquire competencies on how to solve complex problems, analyze data, and come up with efficient solutions. Shall we start this wonderful journey together! learnfasta.com terms of use, Copyright 2025 All Rights Reserved.