-
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 (RegExp) in JavaScript are patterns used to match, search, and manipulate strings. They are extremely powerful for validating input, parsing text, and performing replacements.
RegExp can be confusing at first, but once you understand the syntax and methods, it becomes a versatile tool for string operations.
JavaScript supports two ways to create regular expressions:
Using a literal notation: /pattern/flags
Using the RegExp constructor: new RegExp("pattern", "flags")
// Literal notation
let regex1 = /hello/;
// Constructor notation
let regex2 = new RegExp("hello");
// Testing the regex
console.log(regex1.test("hello world")); // Logs: true
console.log(regex2.test("hi there")); // Logs: false
Literal notation is faster and more readable.
Constructor notation is useful when the pattern is dynamic.
Flags modify how the pattern is applied:
g
– Global search (find all matches)
i
– Case-insensitive search
m
– Multiline search
s
– Allows dot .
to match newline characters
u
– Unicode mode
y
– Sticky search (matches from lastIndex only)
let text = "Hello hello";
let regex = /hello/gi; // Case-insensitive and global
console.log(text.match(regex)); // Logs: ["Hello", "hello"]
let regex = /a/; // Matches the character 'a'
console.log(regex.test("apple")); // true
console.log(regex.test("banana")); // true
console.log(regex.test("cherry")); // false
.
– Matches any single character except newline
\d
– Matches any digit [0-9]
\D
– Matches any non-digit
\w
– Matches any word character [a-zA-Z0-9_]
\W
– Matches any non-word character
\s
– Matches any whitespace character
\S
– Matches any non-whitespace character
let regex = /\d/;
console.log(regex.test("abc123")); // true
Quantifiers define how many times a character or group can occur:
*
– Zero or more times
+
– One or more times
?
– Zero or one time
{n}
– Exactly n times
{n,}
– At least n times
{n,m}
– Between n and m times
let regex = /\d{2,4}/; // Match 2 to 4 digits
console.log("12345".match(regex)); // Logs: ["1234"]
Character sets [ ]
allow matching any character inside:
let regex = /[aeiou]/g; // Match vowels
console.log("hello world".match(regex)); // Logs: ["e","o","o"]
Ranges [a-z]
match characters in a specific range.
Anchors match positions in the string:
^
– Start of string
$
– End of string
let regex = /^Hello/;
console.log(regex.test("Hello world")); // true
console.log(regex.test("world Hello")); // false
Useful for validating input formats.
Parentheses ( )
are used to group expressions and capture matches:
let regex = /(ab)+/; // Matches one or more repetitions of "ab"
console.log("ababab".match(regex)); // Logs: ["ababab"]
Captured groups can be accessed using match
or RegExp.$1
, $2
, etc.
\b
– Word boundary
\B
– Non-word boundary
(?=...)
– Positive lookahead
(?!...)
– Negative lookahead
let regex = /\d(?=px)/; // Match digits only if followed by "px"
console.log("10px 20em".match(regex)); // Logs: ["1"]
Lookahead is useful for conditional matching without including it in the result.
test()
Returns true
if the pattern matches the string:
let regex = /hello/i;
console.log(regex.test("Hello World")); // true
exec()
Returns an array containing the first match and captured groups:
let regex = /(\d+)/;
let result = regex.exec("I have 42 apples");
console.log(result); // Logs: ["42", "42"]
match()
– Returns all matches
replace()
– Replaces matched parts
search()
– Returns the index of the match
split()
– Splits string using regex
let text = "apple, banana, cherry";
console.log(text.split(/, /)); // ["apple", "banana", "cherry"]
let replaced = text.replace(/banana/, "orange");
console.log(replaced); // "apple, orange, cherry"
function validateEmail(email) {
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;
return regex.test(email);
}
console.log(validateEmail("test@example.com")); // true
console.log(validateEmail("invalid-email")); // false
The regex checks for a basic email format, ensuring a valid username, @
symbol, domain, and extension.
Regular expressions allow pattern matching and manipulation of strings.
Use literal or constructor notation to define regex.
Flags control global search, case sensitivity, multiline, etc.
Patterns include characters, metacharacters, quantifiers, anchors, groups, and lookaheads.
Methods like test()
, exec()
, match()
, replace()
, search()
, and split()
are essential for working with RegExp.
RegExp is widely used for validation, parsing, text replacement, and data extraction.
Mastering JavaScript RegExp is crucial for efficient text processing and complex string manipulations in modern web development.
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