String Search
Find text inside strings with includes, indexOf and more.
Syntax
str.includes('text')
str.indexOf('text')You can search inside strings:
includes()— returns true if the text is found.indexOf()— returns the position, or-1if not found.startsWith()/endsWith()— check the beginning or end.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Find the position of a search keyword within article text to scroll it into view.
- Test whether a filename ends with .pdf before allowing it to be uploaded.
- Extract a query parameter value from a URL string using indexOf and slice.
More examples
indexOf to find a substring
Uses indexOf to locate 'port' within a log message, returning -1 if not present.
const text = "Error: connection refused at port 5432";
const idx = text.indexOf("port");
console.log(idx); // 30
console.log(idx !== -1 ? "found" : "not found");search with a regex
Uses search() with a regular expression to find the position of a 4-digit year in a filename.
const filename = "report_2024-Q3.xlsx";
const pos = filename.search(/\d{4}/);
console.log(pos); // 7 – position of the 4-digit yearmatch to extract substrings
Uses match() with the global flag to extract all IP addresses from a log string into an array.
const log = "IPs: 192.168.1.1 and 10.0.0.5";
const ips = log.match(/\d+\.\d+\.\d+\.\d+/g);
console.log(ips); // ["192.168.1.1", "10.0.0.5"]
Discussion