JavaScript String Search
JavaScript provides several methods for searching within strings to find specific substrings or characters. These methods include indexOf()
, lastIndexOf()
, search()
, and match()
.
1. indexOf()
Returns the index of the first occurrence of a specified substring within the string.
Example:
const str = "Hello, world!";
console.log(str.indexOf("world")); // Output: 7
2. lastIndexOf()
Returns the index of the last occurrence of a specified substring within the string.
Example:
const str = "Hello, world, world!";
console.log(str.lastIndexOf("world")); // Output: 13
3. search()
Searches for a specified substring within the string and returns the index of the first match.
Example:
const str = "Hello, world!";
console.log(str.search("world")); // Output: 7
4. match()
Searches the string for a specified pattern and returns an array of matches.
Example:
const str = "The rain in Spain falls mainly in the plain.";
const regex = /ain/g;
console.log(str.match(regex)); // Output: ["ain", "ain", "ain", "ain"]
These are some of the string search methods available in JavaScript. Each method has its specific use case and can be utilized to find substrings or patterns within strings efficiently.