-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
There are two main ways to create a regular expression in JavaScript: using a literal and using the RegExp constructor.
const pattern = /hello/;
console.log(pattern.test("hello world")); // true
RegExp Constructorconst 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().
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"]
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
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"]
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
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
Splits a string using a pattern as a delimiter.
const text = "Aarushi,Priya,Saanvi";
const names = text.split(/,/);
console.log(names); // ["Aarushi", "Priya", "Saanvi"]
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"]
* – 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"]
^ – Start of string
$ – End of string
const text = "Aarushi is here";
console.log(/^Aarushi/.test(text)); // true
console.log(/here$/.test(text)); // true
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
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
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
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
const text = "Priya scored 95, Saanvi scored 88";
const numbers = text.match(/\d+/g);
console.log(numbers); // ["95", "88"]
const text = "Hello Aarushi, Hello Priya";
const newText = text.replace(/Hello/g, "Hi");
console.log(newText); // Hi Aarushi, Hi Priya
const text = "Aarushi|Priya|Saanvi";
const names = text.split(/\|/);
console.log(names); // ["Aarushi", "Priya", "Saanvi"]
const text = "Aarushi is a student";
console.log(/^Aarushi/.test(text)); // true
console.log(/student$/.test(text)); // true
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.
Write a regular expression to test if a string contains the word "JavaScript" (case-insensitive).
Use a regular expression to extract all digits from the string "I have 2025 apples and 30 oranges".
Create a regex that matches a valid email address and test it on "test@example.com" and "invalid-email".
Use a regular expression to replace all spaces in the string "Hello World From JS" with hyphens (-).
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.
Create a regex to validate a US phone number format like "123-456-7890" and test it on a valid and invalid number.
Use regex to check if a string starts with "Hello" and ends with "JS" in "Hello from JavaScript JS".
Write a regex to split the string "apple,banana;cherry|date" by commas, semicolons, or pipes.
Create a regex to match all HTML tags in the string "<div>Hello</div><p>World</p>" and log the results.
Use regex with lookahead to find digits in "50px, 20em, 100%" that are followed by "px" only.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
