Introduction
Check if a String Contains a Substring in JavaScript is a basic but very common task in web development. From filtering content to validating input, this simple snippet will help you handle it easily with modern JavaScript.
How to Check if a String Contains a Substring in JavaScript
Use the includes()
method, available on all modern JavaScript string objects:
const sentence = ‘The quick brown fox jumps over the lazy dog’;
const hasWord = sentence.includes(‘fox’);
console.log(hasWord); // true
How This Works
The Check if a String Contains a Substring in JavaScript example uses the includes()
method. It returns true
if the substring is found and false
otherwise.
Why Use This?
Check if a String Contains a Substring in JavaScript helps keep your code readable and concise compared to older indexOf techniques.
Common Mistake
Remember: includes()
is case-sensitive. “Fox” and “fox” are not equal.
Pro Tip
Use .toLowerCase()
on both strings if you want a case-insensitive check.