What is Regex?

Regex, short for Regular Expression, is a powerful tool used in JavaScript and many other programming languages to search, match, and manipulate strings based on specific text patterns.

Illustration of What is Regex?
Illustration of What is Regex?

💡 Key Idea

Think of regex as a specialized search tool that can find complex combinations of characters, not just exact words.

Regex patterns are made up of characters and special symbols that define the rules for matching text. This allows you to:

  • Check if a string contains a certain pattern
  • Extract parts of a string that match a pattern
  • Replace or split strings based on patterns
Common Regex Components
SymbolMeaning
.Matches any single character except newline
*Matches zero or more occurrences of the preceding element
+Matches one or more occurrences of the preceding element
?Makes the preceding element optional (zero or one occurrence)
^Matches the start of a string
$Matches the end of a string
[abc]Matches any one character inside the brackets (a, b or c)
\dMatches any digit (0-9)
\wMatches any word character (letters, digits, underscore)
\sMatches any whitespace character (space, tab, newline)

💡 Regex in JavaScript

Regex patterns are created using either /pattern/flags syntax or by using the RegExp constructor.

📌 Deep Dive: Simple Regex Test

JAVASCRIPT
const pattern = /cat/;
console.log(pattern.test("I have a cat."));  // true
console.log(pattern.test("I have a dog."));  // false
Output
true
false

Here, the regex /cat/ looks for the substring "cat" anywhere in the text.

⚠️ Important

Regex can be tricky—small changes in a pattern can drastically change what it matches. Always test your regex carefully.

Regex is a fundamental skill that helps automate many text-processing tasks efficiently.