JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Regular Expression Syntax and Examples

Regular expressions are patterns used to match character combinations in strings. In JavaScript, these patterns are used with the RegExp methods, such as test() and exec(), as well as with the String methods, such as match() and replace(). Understanding the syntax is crucial for effective pattern matching.

Syntax

Follow the syntax below to create regular expressions.

var patt = /pattern/modifiers;
  • You can write the regular expression pattern between two backslashes ('/'). After that, you can write modifiers to use with regular expression.

Components of regular expressions

Here's a breakdown of the fundamental components of regular expressions in JavaScript:

Modifiers

Modifiers alter how the searching behavior of a regular expression is conducted in JavaScript. Here's a detailed table explaining each modifier:

ExpressionDescription
gGlobal search - finds all matches rather than stopping after the first match.
iCase insensitive search - treats uppercase and lowercase letters as equivalent.
mMulti-line search - causes start and end characters (^ and $) to match the start and end of a line, not just the start and end of the string.

Brackets

Brackets are used to define a group of characters to match in a string. Here are the different types of bracket expressions:

ExpressionDescription
[abc]Matches any one character from the set {a, b, c}.
[^abc]Matches any one character not in the set {a, b, c}.
[0-9]Matches any digit from 0 to 9.
[a-z]Matches any lowercase letter from a to z.
[A-Z]Matches any uppercase letter from A to Z.
[A-z]Matches any letter from A to z.
[a-zA-Z]Matches any letter from a to z or A to Z.

Quantifiers

Quantifiers specify how many instances of a character, group, or character class must be present in the input for a match to be found.

ExpressionDescription
n+Matches any string that contains at least one n.
n*Matches any string that contains zero or more occurrences of n.
n?Matches any string that contains zero or one occurrence of n.
n{x}Matches exactly x occurrences of the item n.
n{x,}Matches x or more occurrences of the item n.
n{x,y}Matches at least x but no more than y occurrences of the item n.

Metacharacters

Metacharacters are characters with a special meaning in the context of a regular expression.

ExpressionDescription
.Matches any single character except newline \n.
\wMatches any word character (equivalent to [a-zA-Z0-9_]).
\WMatches any non-word character (anything other than what \w matches).
\dMatches any digit (equivalent to [0-9]).
\DMatches any non-digit character.
\sMatches any whitespace character (spaces, tabs, line breaks).
\SMatches any non-whitespace character.
\bMatches a word boundary where a word character is followed by a non-word character or vice versa.
\BMatches a position where \b does not apply.
^Matches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled.
$Matches the end of the string, or the end of a line if the multiline flag (m) is enabled.

Each of these tables provides a comprehensive look at the different elements that make up regular expressions in JavaScript. Understanding how to use each component allows for the creation of flexible and powerful text searching and manipulation functionality in your JavaScript applications.

Creating Regular Expressions

Regular expressions are powerful tools for validating input data such as email addresses and phone numbers. Below, we explain how to construct regular expressions for these common validation tasks, gradually increasing in complexity.

Basic Email Validation

A basic regular expression to validate a simple email format:

let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  • Explanation of the Regular Expression:
    • ^: Asserts the start of the line.
    • [a-zA-Z0-9._-]+: Matches one or more alphanumeric characters including dots, underscores, and hyphens.
    • @: Literal character that must appear once, separating the local part and the domain part of the email.
    • [a-zA-Z0-9.-]+: Matches one or more alphanumeric characters including dots and hyphens for the domain name.
    • \.: Escapes the dot because a non-escaped dot means any character in regex.
    • [a-zA-Z]{2,6}: Matches between 2 and 6 alphabetic characters for the domain suffix (like .com, .org).
    • $: Asserts the end of the line.

Example

Javascript
Javascript

. . . .
  • This example checks if the string email matches the pattern defined. Given the email is properly formatted, it returns true.

Basic Phone Number Validation

A regular expression to validate a US phone number format:

let phonePattern = /^\d{3}-\d{3}-\d{4}$/;
  • Explanation:
    • ^\d{3}: Starts with exactly three digits.
    • -\d{3}: Followed by a hyphen and exactly three more digits.
    • -\d{4}$: Ends with a hyphen and exactly four digits.

Example

Javascript
Javascript

. . . .
  • This example checks for a specific format of a US phone number.

These examples show how you can construct regular expressions from simple to complex to validate common forms of data such as emails and phone numbers. By understanding and using regular expressions effectively, you can enhance data validation processes in your JavaScript applications.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next