JS Tutorial



JS REGEX


JavaScript Regular Expressions (RegEx) 📜

A regular expression (RegEx) is a pattern used to match character combinations in strings. Regular expressions are used for pattern matching with strings, such as validating inputs, replacing text, or searching for specific patterns in data.

🔄 Basic Syntax

In JavaScript, regular expressions are created using the /pattern/ syntax or by using the RegExp() constructor:

  • Literal Notation: /abc/ matches the exact string abc.
  • RegExp Constructor: new RegExp('abc') does the same as the literal notation.

⚙️ Special Characters

Regular expressions use special characters to define search patterns:

  • . (dot): Matches any single character except newline.
  • \d: Matches any digit (0-9).
  • \w: Matches any word character (letters, digits, and underscores).
  • \s: Matches any whitespace character (spaces, tabs, newlines).
  • ^: Matches the beginning of a string.
  • $: Matches the end of a string.

🔄 Live Example: Test a Regular Expression


Result will appear here.

📌 Common RegEx Patterns

Here are some commonly used regular expression patterns in JavaScript:

  • Validate an Email: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
  • Validate a Phone Number: /^\d{3}-\d{3}-\d{4}$/
  • Match a URL: /https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/
  • Match a Date (DD/MM/YYYY): /\d{2}\/\d{2}\/\d{4}/

⚙️ Methods for Using RegEx in JavaScript

JavaScript provides several methods for working with regular expressions:

  • test(): Tests if a string matches the regular expression. Returns true or false.
  • exec(): Executes a search for a match and returns the result in an array, or null if no match is found.
  • match(): Returns an array of all matches in a string.
  • replace(): Replaces matched substrings with a new string.
  • split(): Splits a string into an array of substrings based on a regular expression.

📌 Live Example: Replace Text Using RegEx


Replaced text will appear here.

⚠️ RegEx Flags

RegEx can be modified using flags to customize its behavior:

  • g (global): Matches all occurrences in the string, not just the first one.
  • i (ignore case): Makes the match case-insensitive.
  • m (multiline): Allows matching across multiple lines.

📌 Live Example: Test Case-Insensitive Match


Result will appear here.
Note: Regular expressions are powerful tools, but they can also be tricky to master. Practice using them to understand their behavior better.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review