How to Check if a String Contains a Substring (Case-Insensitive Too)
The idiomatic substring check in Python, JavaScript, Java, C#, Go and SQL, how to do it case-insensitively without locale bugs, and how to match any of several words.
By Software Side Hustles Editorial Team · Published · Updated · 4 min read
Quick answer: Python "needle" in haystack, JavaScript haystack.includes("needle"), Java haystack.contains("needle"), C# haystack.Contains("needle"), Go strings.Contains(haystack, "needle"), SQL col LIKE '%needle%'. Each returns a boolean. For case-insensitive checks, normalise both sides (casefold() / toLowerCase()) or use the language's ignore-case comparison.
Substring check by language
| Language | Contains | Position (or "not found" value) | Case-insensitive |
|---|---|---|---|
| Python | sub in s | s.find(sub) → -1 | sub.casefold() in s.casefold() |
| JavaScript | s.includes(sub) | s.indexOf(sub) → -1 | s.toLowerCase().includes(sub.toLowerCase()) |
| Java | s.contains(sub) | s.indexOf(sub) → -1 | s.toLowerCase(Locale.ROOT).contains(...) |
| C# | s.Contains(sub) | s.IndexOf(sub) → -1 | s.Contains(sub, StringComparison.OrdinalIgnoreCase) |
| Go | strings.Contains(s, sub) | strings.Index(s, sub) → -1 | strings.Contains(strings.ToLower(s), strings.ToLower(sub)) |
| SQL | col LIKE '%sub%' | POSITION(sub IN col) → 0 | ILIKE (PostgreSQL) or LOWER(col) LIKE ... |
How do I check if a string contains a substring in Python?
s = "Traceback (most recent call last)""recent" in s # True"Recent" in s # False — case-sensitives.find("call") # 23 — index of first match, or -1s.index("missing") # ValueError: substring not founds.count("a") # 4s.startswith(("Trace", "Error")) # True — accepts a tupleUse in for yes/no questions — it is the clearest and fastest. Use find when you need the position and "not found" is normal; index when a missing substring is an error.
For case-insensitive checks prefer casefold() over lower(). It handles cases such as the German ß, which casefolds to ss, so "STRASSE".casefold() == "straße".casefold() is True.
How do I check if a string contains a substring in JavaScript?
const s = "Unexpected token '<'";s.includes("token"); // trues.indexOf("token") !== -1; // true — the pre-ES2015 idioms.toLowerCase().includes("TOKEN".toLowerCase()); // true/token/i.test(s); // true — regex, case-insensitiveA bug that appears in code reviews: if (s.indexOf("x")). indexOf returns 0 when the match is at the start, and 0 is falsy, so the condition fails exactly when the string starts with the substring. Use includes, or compare with !== -1.
If the search term comes from a user, do not drop it into a RegExp unescaped: new RegExp("c++") throws Invalid regular expression: /c++/: Nothing to repeat. Use includes, or escape special characters first.
How do I check if a String contains a substring in Java?
String s = "NullPointerException at line 42";s.contains("Pointer"); // trues.indexOf("line"); // 24s.toLowerCase(Locale.ROOT).contains("nullpointer"); // truePass Locale.ROOT to toLowerCase. With the default locale on a Turkish system, "TITLE".toLowerCase() produces a dotless ı ("tıtle"), and your comparison fails only for Turkish users. For regex with case-insensitivity, use Pattern.compile(Pattern.quote(sub), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).
s.contains(null) throws a NullPointerException; check user input first. See how to fix NullPointerException in Java.
C# and Go
C# has ordinal and culture-aware comparisons built in:
s.Contains("error", StringComparison.OrdinalIgnoreCase);Use Ordinal/OrdinalIgnoreCase for identifiers, file paths and protocol values; use culture-aware comparison for text shown to people.
Go keeps it simple — strings.Contains, strings.HasPrefix, strings.HasSuffix and strings.Index. For case-insensitive equality (not containment), strings.EqualFold(a, b) avoids allocating lowered copies.
How do I check if a string contains any of several words?
keywords = ["timeout", "refused", "reset"]any(k in message for k in keywords)const keywords = ["timeout", "refused", "reset"];keywords.some((k) => message.includes(k));For many keywords against long texts, a single compiled regex (re.compile("|".join(map(re.escape, keywords)))) or an Aho–Corasick library is much faster than looping. Note re.escape — without it, a keyword such as c++ breaks the pattern.
How do I search for a substring in SQL?
SELECT * FROM products WHERE name LIKE '%cable%';SELECT * FROM products WHERE name ILIKE '%cable%'; -- PostgreSQL, case-insensitiveSELECT * FROM products WHERE LOWER(name) LIKE '%cable%'; -- portableTwo caveats. First, % and _ are wildcards; if users can type them, escape them (LIKE '%50\%%' ESCAPE '\'). Second, a leading % prevents a normal B-tree index from being used, so the query scans the whole table. For search over large tables, use full-text search (PostgreSQL tsvector, MySQL FULLTEXT) or a trigram index (pg_trgm). And always pass the search term as a parameter — see preventing SQL injection.
Edge cases worth knowing
- The empty string is contained in every string.
"" in "abc"isTrue,"abc".includes("")istrue. If an empty search box should match nothing, handle it explicitly. - Whole words.
"cat" in "concatenate"isTrue. Use a word-boundary regex such as\bcat\bwhen you mean the word. - Accents.
"café".includes("cafe")isfalse. Normalise withnormalize("NFD")and strip combining marks if accent-insensitive search is required.
Frequently asked questions
Which is faster, includes or indexOf?
They perform the same search; choose includes for readability when you only need a boolean.
Does Python have a contains method?
Strings implement __contains__, which is what the in operator calls. Use in rather than calling __contains__ directly.
How do I find all occurrences of a substring?
Python: [m.start() for m in re.finditer(re.escape(sub), s)]. JavaScript: [...s.matchAll(new RegExp(escaped, "g"))].map((m) => m.index).
Where this skill pays off
The if (s.indexOf(x)) bug and the Turkish-locale bug are small enough to slip past a quick review and costly enough to matter. Spotting them in AI-generated code is the day-to-day of paid code evaluation — learn how it works in what coding-focused AI data annotation is.