Loading lessons...
String Search
String Search
JavaScript offers several methods to search inside strings.
indexOf
Finds the first position of text, or -1 if not found:
"Hello World".indexOf("World"); // 6
"Hello World".indexOf("xyz"); // -1
Positions start at 0.
lastIndexOf
Finds the last position of text:
"a-b-c".lastIndexOf("-"); // 3
includes
Checks if text exists, returning a boolean:
"Hello".includes("ell"); // true
startsWith and endsWith
Check how a string begins or ends:
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true
search with patterns
search() works like indexOf but accepts regular expressions:
"Hello".search(/ell/); // 1
TL;DR
- indexOf returns the first position or -1.
- includes returns true/false.
- startsWith and endsWith check the edges.
- search accepts regular expressions.