Regular Expressions (RegExp) in JavaScript are used to search, match, and manipulate text based on patterns. They are widely used for form validation, searching text, extracting data, and replacing content. This guide explains RegExp from basics with simple language and practical examples.

What Is RegExp in JavaScript?

A Regular Expression (RegExp) is a pattern used to match characters in strings.

Common uses:

  • Validate email, phone number, password

  • Search specific words in text

  • Extract parts of a string

  • Replace text based on a pattern

How to Create a RegExp in JavaScript

1. Using Literal Syntax

2. Using RegExp Constructor

Explanation:

Both methods create a regular expression that matches the word hello.

Basic RegExp Methods in JavaScript

RegExp.test()

Explanation:

Returns true if the pattern is found in the string, otherwise false.

String.match()

Explanation:

Returns all matches of the pattern as an array.

String.search()

Explanation:

Returns the index of the first match, or -1 if not found.

String.replace()

Explanation:

Replaces the matched text with the given value.

RegExp Flags (Modifiers)

FlagMeaning
gGlobal search (find all matches)
iCase-insensitive search
mMulti-line search

Example with Flags

Explanation:

Finds all matches of hello ignoring case.

Common RegExp Patterns

Match Digits

Explanation:

\d+ matches one or more digits.

Match Letters Only

Explanation:

Matches only alphabet characters.

Check if String Starts with a Word

Explanation:

^ checks the beginning of the string.

Check if String Ends with a Word

Explanation:

$ checks the end of the string.

Simple Validation Examples

Validate Email Format

Explanation:

Checks basic email structure.

Common RegExp Symbols

SymbolMeaning
.Any single character
\dDigit
\wWord character (letters, digits, underscore)
+One or more
*Zero or more
?Zero or one
^Start of string
$End of string

Conclusion

Regular Expressions in JavaScript provide a powerful way to work with text using patterns. By learning basic RegExp syntax, flags, and methods like test(), match(), and replace(), text validation and manipulation become simple and efficient in JavaScript applications