JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript RegExp


Regular expressions, often abbreviated as RegExp, are powerful tools in JavaScript used for pattern matching within strings. They allow developers to search, match, replace, and validate text efficiently. RegExp is widely used for tasks such as input validation, data parsing, text extraction, and complex search operations. Understanding RegExp is essential for building applications that handle dynamic text or require precise string manipulation.

In this tutorial, you will learn about JavaScript RegExp, how to create and use regular expressions, practical examples, common mistakes, best practices, and real-world applications.

Why RegExp Is Important

Regular expressions are important because they allow you to:

  • Validate user input such as emails, phone numbers, or passwords

  • Search for patterns in large text efficiently

  • Replace or extract specific substrings from text

  • Perform complex string manipulations in a concise way

  • Build tools for text analysis, parsing, or filtering

Without RegExp, many text-processing tasks would require lengthy loops and conditional checks, which are less efficient and harder to maintain.

Creating Regular Expressions

There are two main ways to create a regular expression in JavaScript: using a literal and using the RegExp constructor.

Using a Regular Expression Literal

const pattern = /hello/;
console.log(pattern.test("hello world")); // true

Using the RegExp Constructor

const pattern = new RegExp("hello");
console.log(pattern.test("hello world")); // true

Both methods create a RegExp object that can be used with string methods such as test(), match(), replace(), search(), and split().

RegExp Flags

Flags modify the behavior of regular expressions:

  • g – Global search (matches all occurrences)

  • i – Case-insensitive search

  • m – Multi-line search

  • s – Dot matches newline

  • u – Treat pattern as Unicode

  • y – Sticky search (matches from lastIndex only)

const pattern = /hello/gi;
console.log("Hello hello".match(pattern)); // ["Hello", "hello"]

Common Methods

test()

Checks if a pattern exists in a string. Returns true or false.

const pattern = /Aarushi/;
console.log(pattern.test("My name is Aarushi")); // true
console.log(pattern.test("My name is Priya"));   // false

match()

Retrieves the matched string(s) from a text.

const text = "I have Aarushi and Priya in the class";
const result = text.match(/Aarushi|Priya/g);
console.log(result); // ["Aarushi", "Priya"]

replace()

Replaces matched patterns with a new string.

const text = "Hello Aarushi, Hello Priya";
const newText = text.replace(/Hello/g, "Hi");
console.log(newText); // Hi Aarushi, Hi Priya

search()

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

const text = "I love JavaScript";
console.log(text.search(/JavaScript/)); // 7
console.log(text.search(/Python/));     // -1

split()

Splits a string using a pattern as a delimiter.

const text = "Aarushi,Priya,Saanvi";
const names = text.split(/,/);
console.log(names); // ["Aarushi", "Priya", "Saanvi"]

Character Classes and Patterns

Regular expressions use special characters to define patterns.

  • . – Any character except newline

  • \d – Digit (0–9)

  • \w – Word character (letters, digits, underscore)

  • \s – Whitespace

  • \b – Word boundary

  • \D – Non-digit

  • \W – Non-word character

  • \S – Non-whitespace

const text = "Aarushi123 Priya456";
const digits = text.match(/\d+/g);
console.log(digits); // ["123", "456"]

Quantifiers

  • * – 0 or more occurrences

  • + – 1 or more occurrences

  • ? – 0 or 1 occurrence

  • {n} – Exactly n occurrences

  • {n,} – At least n occurrences

  • {n,m} – Between n and m occurrences

const text = "aa aaa aaaa aaaaa";
const match = text.match(/a{3}/g);
console.log(match); // ["aaa", "aaa"]

Anchors

  • ^ – Start of string

  • $ – End of string

const text = "Aarushi is here";
console.log(/^Aarushi/.test(text)); // true
console.log(/here$/.test(text));    // true

Common Mistakes

  • Forgetting to escape special characters like ., *, +, ?, ^, $, [, ], (, )

  • Using global flag with test() without resetting lastIndex

  • Misusing greedy quantifiers leading to unexpected matches

  • Ignoring case sensitivity when needed

  • Overcomplicating regular expressions instead of using simple string methods

Best Practices

  • Use the simplest pattern that solves the problem

  • Test regular expressions with multiple input cases

  • Escape special characters when necessary

  • Use flags appropriately for case sensitivity and global matches

  • Comment complex regular expressions for clarity

Real-World Applications

  • Validating email addresses, phone numbers, and postal codes

  • Searching and replacing text in editors or web applications

  • Extracting data from logs, CSV, or JSON files

  • Filtering input to prevent invalid data or security issues

  • Parsing and analyzing text content for patterns

Practical Examples

Example 1: Validating Email

const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,4}$/;
console.log(emailPattern.test("aarushi@example.com")); // true
console.log(emailPattern.test("aarushi@.com"));        // false

Example 2: Extracting Numbers

const text = "Priya scored 95, Saanvi scored 88";
const numbers = text.match(/\d+/g);
console.log(numbers); // ["95", "88"]

Example 3: Replacing Text

const text = "Hello Aarushi, Hello Priya";
const newText = text.replace(/Hello/g, "Hi");
console.log(newText); // Hi Aarushi, Hi Priya

Example 4: Splitting Strings

const text = "Aarushi|Priya|Saanvi";
const names = text.split(/\|/);
console.log(names); // ["Aarushi", "Priya", "Saanvi"]

Example 5: Checking Start and End

const text = "Aarushi is a student";
console.log(/^Aarushi/.test(text)); // true
console.log(/student$/.test(text)); // true

Summary of JavaScript RegExp

JavaScript RegExp provides a versatile and efficient way to work with strings using patterns. It allows searching, matching, replacing, and validating text, making it essential for handling dynamic content and user input. By understanding RegExp syntax, flags, character classes, and quantifiers, developers can perform complex string operations with minimal code. Following best practices ensures that regular expressions remain readable, maintainable, and effective in real-world applications.


Practice Questions

  1. Write a regular expression to test if a string contains the word "JavaScript" (case-insensitive).

  2. Use a regular expression to extract all digits from the string "I have 2025 apples and 30 oranges".

  3. Create a regex that matches a valid email address and test it on "test@example.com" and "invalid-email".

  4. Use a regular expression to replace all spaces in the string "Hello World From JS" with hyphens (-).

  5. Write a regex to match all words that start with the letter b in the string "banana band ball bat" and return them as an array.

  6. Create a regex to validate a US phone number format like "123-456-7890" and test it on a valid and invalid number.

  7. Use regex to check if a string starts with "Hello" and ends with "JS" in "Hello from JavaScript JS".

  8. Write a regex to split the string "apple,banana;cherry|date" by commas, semicolons, or pipes.

  9. Create a regex to match all HTML tags in the string "<div>Hello</div><p>World</p>" and log the results.

  10. Use regex with lookahead to find digits in "50px, 20em, 100%" that are followed by "px" only.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top