Introduction
String searching is the process of finding whether a particular character, word, or substring exists within a string. JavaScript provides several built-in methods that make searching text simple and efficient.
Searching strings is one of the most common tasks in JavaScript programming. Whether you’re validating user input, checking page titles, processing API responses, or searching log files, string searching methods help you locate text quickly.
For automation engineers, string searching is essential for validating web page content, verifying URLs, checking API responses, locating error messages, and performing assertions in Selenium, Playwright, and Cypress.
What is String Searching?
String searching refers to locating the position or existence of a character or substring within a string.
JavaScript provides several methods for this purpose, including:
-
includes() -
indexOf() -
lastIndexOf() -
startsWith() -
endsWith() -
search()
Each method serves a different purpose depending on the requirement.
Why Do We Use String Searching?
String searching helps developers:
-
Check whether text exists.
-
Find the position of text.
-
Validate user input.
-
Verify URLs.
-
Search API responses.
-
Perform text-based validations.
includes()
The includes() method checks whether a string contains a specified substring.
Syntax
string.includes(searchString)
Example
let language = "JavaScript";
console.log(language.includes("Script"));
Output
true
indexOf()
The indexOf() method returns the index of the first occurrence of a substring.
If the substring is not found, it returns -1.
Syntax
string.indexOf(searchString)
Example
let text = "JavaScript";
console.log(text.indexOf("S"));
Output
4
lastIndexOf()
The lastIndexOf() method returns the last occurrence of a substring.
Example
let text = "banana";
console.log(text.lastIndexOf("a"));
Output
5
startsWith()
Checks whether a string starts with specified text.
Example
let url = "https://example.com";
console.log(url.startsWith("https"));
Output
true
endsWith()
Checks whether a string ends with specified text.
Example
let fileName = "report.pdf";
console.log(fileName.endsWith(".pdf"));
Output
true
search()
The search() method searches for a pattern or regular expression and returns its index.
Example
let text = "Learning JavaScript";
console.log(text.search("Java"));
Output
9
Real-World Example
Suppose an application validates email addresses.
let email = "employee@company.com";
console.log(email.includes("@"));
Output
true
Another example:
Validate file type.
let file = "invoice.pdf";
console.log(file.endsWith(".pdf"));
Output
true
Another example:
Check whether a website uses HTTPS.
let website = "https://example.com";
console.log(website.startsWith("https"));
Output
true
Automation Testing Example
Automation engineers frequently use string searching methods while validating UI elements, URLs, API responses, and log messages.
Playwright Example
Verify that the page title contains a keyword.
const title = await page.title();
console.log(title.includes("Dashboard"));
Selenium Example
Validate the current URL.
const url = await driver.getCurrentUrl();
console.log(url.startsWith("https"));
Cypress Example
Check whether the URL contains a page name.
const url = "https://example.com/dashboard";
console.log(url.includes("dashboard"));
API Testing Example
Validate the response message.
const response = {
message: "Login Successful"
};
console.log(response.message.includes("Successful"));
Output
true
Data-Driven Testing Example
Search usernames.
const users = [
"administrator",
"manager",
"tester"
];
for (const user of users) {
console.log(user.startsWith("a"));
}
Output
true
false
false
Comparison of String Searching Methods
| Method | Purpose | Return Value |
|---|---|---|
includes() |
Checks whether text exists | true or false |
indexOf() |
Finds first occurrence | Index or -1 |
lastIndexOf() |
Finds last occurrence | Index or -1 |
startsWith() |
Checks beginning of string | true or false |
endsWith() |
Checks end of string | true or false |
search() |
Searches using text or regex | Index or -1 |
Common Mistakes
Assuming Searches Are Case-Sensitive
let text = "JavaScript";
console.log(text.includes("javascript"));
Output
false
The search is case-sensitive.
Correct:
console.log(text.includes("JavaScript"));
Confusing includes() and indexOf()
Incorrect:
if (text.indexOf("Java")) {
console.log("Found");
}
This can produce incorrect results because indexOf() returns 0 when the text is found at the beginning, and 0 is treated as false.
Correct:
if (text.includes("Java")) {
console.log("Found");
}
or
if (text.indexOf("Java") !== -1) {
console.log("Found");
}
Expecting includes() to Return an Index
let text = "JavaScript";
console.log(text.includes("Script"));
Output
true
includes() returns a boolean, not an index.
Best Practices
Use includes() for Existence Checks
When you only need to know whether text exists, prefer includes().
Use indexOf() When You Need the Position
If the exact location of the substring is important, use indexOf().
Use startsWith() and endsWith() for Validation
These methods make URL and file extension validation more readable.
Be Aware of Case Sensitivity
Convert strings to the same case when performing case-insensitive searches.
text.toLowerCase().includes("javascript")
Conclusion
JavaScript provides several powerful methods for searching strings, making it easy to locate text, validate input, and process data efficiently. Methods like includes(), indexOf(), lastIndexOf(), startsWith(), endsWith(), and search() cover a wide range of search requirements.
For automation engineers, these methods are indispensable for validating page titles, checking URLs, verifying API responses, processing test data, and performing assertions. Understanding when to use each method will help you write cleaner, more reliable, and more maintainable automation scripts.
Frequently Asked Questions (FAQs)
What is string searching in JavaScript?
String searching is the process of finding characters or substrings within a string.
Which method checks whether a string contains text?
string.includes("text")
Which method returns the first occurrence of a substring?
string.indexOf("text")
Which method checks whether a string starts with a specific value?
string.startsWith("text")
Which method checks whether a string ends with a specific value?
string.endsWith("text")
Why is string searching important in automation testing?
Automation engineers use string searching to validate page titles, URLs, API responses, log messages, error messages, and other text-based data during automated testing.
Key Takeaways
-
String searching helps locate text within strings.
-
includes()checks whether text exists. -
indexOf()returns the first occurrence of a substring. -
lastIndexOf()returns the last occurrence. -
startsWith()checks the beginning of a string. -
endsWith()checks the end of a string. -
search()supports searching with text and regular expressions. -
Most string searching methods are case-sensitive.
-
These methods are widely used in JavaScript development and automation testing.
-
Mastering string searching is essential for effective text validation and processing.
