Js String Search in JavaScript
? JavaScript String Search Methods
JavaScript provides several methods to search inside strings to find the position of substrings or patterns.
Common String Search Methods
| Method | Description | Example | Output |
|---|---|---|---|
indexOf(searchValue) | Returns the first index of searchValue or -1 if not found | "hello".indexOf("l") | 2 |
lastIndexOf(searchValue) | Returns the last index of searchValue or -1 if not found | "hello".lastIndexOf("l") | 3 |
search(regex) | Searches for a match using a regular expression, returns index or -1 | "hello".search(/l/) | 2 |
includes(searchString) | Returns true if string contains searchString, else false | "hello".includes("ll") | true |
match(regex) | Returns an array of matches for regex or null if no match | "hello".match(/l/g) | ["l", "l"] |
startsWith(searchString) | Checks if string starts with searchString (true/false) | "hello".startsWith("he") | true |
endsWith(searchString) | Checks if string ends with searchString (true/false) | "hello".endsWith("lo") | true |
Examples
let text = "Hello, world!";console.log(text.indexOf("o")); // 4console.log(text.lastIndexOf("o")); // 8console.log(text.includes("world")); // trueconsole.log(text.startsWith("Hell")); // trueconsole.log(text.endsWith("!")); // trueconsole.log(text.search(/world/)); // 7let matches = text.match(/o/g);console.log(matches); // ["o", "o"]If you want, I can help with regular expression based searching or advanced string matching!