iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS String Search

Five built-in methods find substrings or check for their presence. Each has a small niche.

The search methods

MethodReturnsUse it for
indexOf(sub, [from])Position of first match, or -1Need the index.
lastIndexOf(sub)Position of last match, or -1Searching from the right.
includes(sub)Boolean"Does it contain X?"
startsWith(prefix)BooleanPrefix test (paths, URLs).
endsWith(suffix)BooleanFile extensions.
search(regex)Index of first regex match, or -1Pattern, not literal.
match(regex)Array of matches, or nullCapture groups, all matches with /g.
matchAll(regex)Iterator of all match arraysLoop 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://')) { /* … */ }

Test yourself

Q1. Test whether a path begins with "/api/" with…
Q2. Get every match of a regex with `/g` flag with…
Q3. Iterate every match with capture groups using…

Discussion

Loading…