JS String Search
Five built-in methods find substrings or check for their presence. Each has a small niche.
The search methods
| Method | Returns | Use it for |
|---|---|---|
indexOf(sub, [from]) | Position of first match, or -1 | Need the index. |
lastIndexOf(sub) | Position of last match, or -1 | Searching from the right. |
includes(sub) | Boolean | "Does it contain X?" |
startsWith(prefix) | Boolean | Prefix test (paths, URLs). |
endsWith(suffix) | Boolean | File extensions. |
search(regex) | Index of first regex match, or -1 | Pattern, not literal. |
match(regex) | Array of matches, or null | Capture groups, all matches with /g. |
matchAll(regex) | Iterator of all match arrays | Loop over every match with its index. |
Examples
JS
const url = "https://docs.example.com/api/v2";
url.startsWith("https://"); // true
url.endsWith(".com"); // false (ends with /v2)
url.includes("api"); // true
url.indexOf("api"); // 24
// Pattern search
const phone = "Call 555-1234 or 555-9999";
phone.match(/\d{3}-\d{4}/g); // ["555-1234", "555-9999"]
for (const m of phone.matchAll(/(\d{3})-(\d{4})/g)) {
console.log(m[0], "area:", m[1]);
}
Note:
indexOf uses strict equality on UTF-16 code units. For complex Unicode (emoji, accents), regex with the u flag handles edge cases better.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS String Search!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Test whether a URL begins with "https://" using a string method.
if (url.
('https://')) { /* … */ }
Two words concatenated: "starts" then "With".
Discussion
Loading…