-
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
Searching within strings is a common requirement in JavaScript, whether you are validating input, finding keywords, or processing text data. JavaScript provides several string methods to search for substrings, locate characters, or match patterns using regular expressions. Understanding these methods allows developers to efficiently manipulate and analyze text content.
In this chapter, you will learn about the different string search methods, practical examples using real-world scenarios, common mistakes, best practices, and applications of string search in JavaScript.
String search is essential for:
Validating user input (emails, names, codes)
Finding keywords or phrases in text
Highlighting or filtering content dynamically
Parsing or extracting information from data
Implementing search functionality in applications
Without effective string search, working with text-based data becomes inefficient and error-prone.
indexOf()The indexOf() method searches for a substring and returns the index of the first occurrence. If the substring is not found, it returns -1.
let message = "Riya submitted her assignment";
console.log(message.indexOf("Riya")); // 0
console.log(message.indexOf("Ananya")); // -1
You can also provide a second argument to specify the starting index for the search:
let text = "Mira and Mira are friends";
console.log(text.indexOf("Mira", 5)); // 9
lastIndexOf()lastIndexOf() returns the index of the last occurrence of a substring.
let text = "Ananya and Ananya are classmates";
console.log(text.lastIndexOf("Ananya")); // 12
search()The search() method searches for a match using a regular expression and returns the index of the first match. Returns -1 if not found.
let text = "Diya is learning JavaScript";
console.log(text.search("Diya")); // 0
// Using regular expression
console.log(text.search(/JavaScript/i)); // 17
Unlike indexOf(), search() can handle complex patterns using regular expressions.
includes()includes() checks if a substring exists in a string and returns true or false.
let student = "Mira Gupta";
console.log(student.includes("Mira")); // true
console.log(student.includes("Diya")); // false
startsWith() and endsWith()These methods check if a string starts or ends with a specified substring.
let student = "Sneha Sharma";
console.log(student.startsWith("Sneha")); // true
console.log(student.endsWith("Sharma")); // true
console.log(student.startsWith("Sharma")); // false
These methods are useful for prefix or suffix validation, such as checking file extensions or titles.
match()The match() method retrieves matches using a regular expression. It can return the first match or all matches depending on the g flag.
let text = "Ananya, Riya, Mira, Diya";
let result = text.match(/a/gi); // Finds all occurrences of 'a'
console.log(result); // ["a","a","a","a","a","a"]
let article = "Diya is learning JavaScript basics";
if (article.includes("JavaScript")) {
console.log("The article contains JavaScript.");
}
let names = "Ananya, Mira, Riya, Diya";
let letterA = names.match(/a/gi);
console.log(`Letter "a" occurs ${letterA.length} times.`);
let fileName = "assignment.docx";
if (fileName.endsWith(".docx")) {
console.log("Valid document file.");
} else {
console.log("Invalid file type.");
}
let message = "Riya, Mira, and Ananya are in the class.";
let pattern = /Riya|Mira/gi;
let found = message.match(pattern);
console.log(found); // ["Riya", "Mira"]
let greeting = "Hello, Diya!";
if (greeting.startsWith("Hello")) {
console.log("Greeting starts correctly.");
}
Using indexOf() when a boolean result is sufficient (use includes() instead)
Ignoring case sensitivity in search operations
Not using the g flag when multiple matches are required with regex
Confusing search() and match(); they return different types of results
Using negative indices incorrectly with indexOf() or lastIndexOf()
Use includes() for simple presence checks
Use search() or match() when working with patterns
Normalize case using toLowerCase() or toUpperCase() before searching if needed
Validate strings before performing search operations
Combine string search with conditional logic for dynamic applications
String search methods are widely used in:
Search bars and filtering lists
Form validation and input checks
Highlighting keywords in articles or messages
Detecting specific patterns in data
File type validation and processing
Text parsing and data extraction
JavaScript string search methods provide powerful tools to locate, match, and validate text. Methods such as indexOf(), search(), includes(), startsWith(), endsWith(), and match() allow developers to handle simple and complex search tasks efficiently. Mastering these methods helps in building interactive applications, validating inputs, and processing text data reliably.
Q1. How do you find the position of the first occurrence of "o" in "hello world"?
Q2. How do you find the index of the last "l" in "hello"?
Q3. Which method would you use to check if "apple" starts with "ap"?
Q4. How do you test if the string "coding" includes the substring "ing"?
Q5. How do you check if a string ends with "!"?
Q6. What does "banana".indexOf("na") return?
Q7. What does "banana".lastIndexOf("na") return?
Q8. How do you search for "e" using a regular expression in the string "elephant"?
Q9. How do you confirm if the word "JavaScript" includes the word "Script"?
Q10. How do you check whether "Hello" starts with "H" and ends with "o"?
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
