Member-only story

Advanced String Search in JavaScript

habtesoft
4 min readDec 3, 2024

--

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.

Not a Medium member? Read this article here

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.

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet