How to check if a string contains a substring in JavaScript
Checking if strings contain specific substrings is fundamental for search functionality, data validation, content filtering, and implementing features like autocomplete or keyword highlighting in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented substring checking extensively in components like search bars, filter systems, and validation logic where detecting specific text patterns is crucial for user experience.
From my extensive expertise, the most modern and intuitive solution is using the ES6 includes()
method, which returns a clear boolean result.
This approach is readable, performant, and specifically designed for substring detection with excellent browser support.
Use the includes()
method to check if a string contains a specific substring.
const text = 'Hello world'
const hasWorld = text.includes('world')
// Result: true
The includes()
method searches the string for the specified substring and returns true
if found, or false
if not found. In this example, 'Hello world'.includes('world')
returns true
because ‘world’ exists within the string. The method is case-sensitive, so text.includes('World')
would return false
. The search starts from the beginning of the string by default, but you can specify a starting position as a second parameter: text.includes('world', 6)
would search starting from index 6.
Best Practice Note:
This is the same approach we use in CoreUI components for implementing search filters, content matching, and validation rules across our component library.
For case-insensitive searches, convert both strings to lowercase first: text.toLowerCase().includes(substring.toLowerCase())
. For more complex pattern matching, consider regular expressions with test()
method. The includes()
method is supported in all modern browsers and provides better readability than alternatives like indexOf() !== -1
.