SoftwareSideHustles
How-To

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

LanguageContainsPosition (or "not found" value)Case-insensitive
Pythonsub in ss.find(sub) → -1sub.casefold() in s.casefold()
JavaScripts.includes(sub)s.indexOf(sub) → -1s.toLowerCase().includes(sub.toLowerCase())
Javas.contains(sub)s.indexOf(sub) → -1s.toLowerCase(Locale.ROOT).contains(...)
C#s.Contains(sub)s.IndexOf(sub) → -1s.Contains(sub, StringComparison.OrdinalIgnoreCase)
Gostrings.Contains(s, sub)strings.Index(s, sub) → -1strings.Contains(strings.ToLower(s), strings.ToLower(sub))
SQLcol LIKE '%sub%'POSITION(sub IN col) → 0ILIKE (PostgreSQL) or LOWER(col) LIKE ...

How do I check if a string contains a substring in Python?

python
s = "Traceback (most recent call last)"
"recent" in s # True
"Recent" in s # False — case-sensitive
s.find("call") # 23 — index of first match, or -1
s.index("missing") # ValueError: substring not found
s.count("a") # 4
s.startswith(("Trace", "Error")) # True — accepts a tuple

Use 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?

javascript
const s = "Unexpected token '<'";
s.includes("token"); // true
s.indexOf("token") !== -1; // true — the pre-ES2015 idiom
s.toLowerCase().includes("TOKEN".toLowerCase()); // true
/token/i.test(s); // true — regex, case-insensitive

A 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?

java
String s = "NullPointerException at line 42";
s.contains("Pointer"); // true
s.indexOf("line"); // 24
s.toLowerCase(Locale.ROOT).contains("nullpointer"); // true

Pass 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:

csharp
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?

python
keywords = ["timeout", "refused", "reset"]
any(k in message for k in keywords)
javascript
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?

sql
SELECT * FROM products WHERE name LIKE '%cable%';
SELECT * FROM products WHERE name ILIKE '%cable%'; -- PostgreSQL, case-insensitive
SELECT * FROM products WHERE LOWER(name) LIKE '%cable%'; -- portable

Two 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" is True, "abc".includes("") is true. If an empty search box should match nothing, handle it explicitly.
  • Whole words. "cat" in "concatenate" is True. Use a word-boundary regex such as \bcat\b when you mean the word.
  • Accents. "café".includes("cafe") is false. Normalise with normalize("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.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy