Member-only story
String search operations are essential for text manipulation, data parsing, and building user-centric applications. Beyond basic searches with indexOf
or includes
, JavaScript offers advanced tools and techniques for string searching. This guide explores these methods, their use cases, and best practices for efficient string searches.
1. Basic String Search Methods
indexOf
Finds the first occurrence of a substring:
const text = "Hello, JavaScript!";
console.log(text.indexOf("JavaScript")); // Output: 7
Limitation: Only returns the first occurrence and doesn’t support complex patterns.
lastIndexOf
Finds the last occurrence of a substring:
const text = "Hello, JavaScript, JavaScript!";
console.log(text.lastIndexOf("JavaScript")); // Output: 19
2. includes
, startsWith
, and endsWith
includes
: Checks if a substring exists.startsWith
: Checks if a string starts with a specific substring.endsWith
: Checks if a string ends with a specific substring.