How to check if a string has a certain piece of text in JavaScript?

JavaScript provides several methods to check if a string contains a specific piece of text. While the older search() method works, modern approaches like includes() are more intuitive and widely used.

Using includes() Method (Recommended)

The includes() method returns true if the string contains the specified text, false otherwise.

let str = "Tutorialspoint: Free Video Tutorials";
let searchText = "Free Video";

if (str.includes(searchText)) {
    document.write("Contains");
} else {
    document.write("Does not contain");
}
Contains

Using search() Method

The search() method returns the index of the first match, or -1 if not found.

let str = "Tutorialspoint: Free Video Tutorials";
let searchText = "Free Video";

if (str.search(searchText) !== -1) {
    document.write("Contains");
} else {
    document.write("Does not contain");
}
Contains

Using indexOf() Method

Similar to search(), indexOf() returns the position of the first occurrence or -1 if not found.

let str = "Tutorialspoint: Free Video Tutorials";
let searchText = "Free Video";

if (str.indexOf(searchText) !== -1) {
    document.write("Contains");
} else {
    document.write("Does not contain");
}
Contains

Case-Sensitive vs Case-Insensitive Search

All methods above are case-sensitive. For case-insensitive searches, convert both strings to lowercase:

let str = "Tutorialspoint: Free Video Tutorials";
let searchText = "free video";

// Case-insensitive check
if (str.toLowerCase().includes(searchText.toLowerCase())) {
    document.write("Contains (case-insensitive)");
} else {
    document.write("Does not contain");
}
Contains (case-insensitive)

Comparison

Method Return Value Best For
includes() Boolean (true/false) Simple presence check
indexOf() Index or -1 Finding position
search() Index or -1 Regex patterns

Conclusion

Use includes() for simple text checks as it's more readable. Use indexOf() or search() when you need the position of the found text.

Updated on: 2026-03-15T20:56:58+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements