How to check if a string contains a substring in JavaScript?
I expected a String.contains() method, but it doesn’t seem to exist. What are the standard methods to check if a string contains a specific substring in JavaScript?
JavaScript has multiple methods to check if a string contains a substring, though it doesn’t have a String.contains() method as you might expect. The most commonly used and recommended methods are includes(), indexOf(), search(), and match().
Contents
- The includes() Method
- The indexOf() Method
- The search() Method
- The match() Method
- Performance Comparison
- Browser Compatibility
- Practical Examples
The includes() Method
The includes() method is the most modern and straightforward way to check if a string contains a substring. It returns true if the string contains the specified substring, and false otherwise.
const str = "Hello, world!";
const substring = "world";
console.log(str.includes(substring)); // true
console.log(str.includes("goodbye")); // false
The includes() method also accepts an optional second parameter that specifies the position to start the search from:
const str = "JavaScript is awesome";
console.log(str.includes("is", 10)); // false (search starts from index 10)
console.log(str.includes("is", 5)); // true (search starts from index 5)
According to FreeCodeCamp, the second argument is the index position where the search begins, with a default value of 0.
The indexOf() Method
The indexOf() method is one of the oldest and most reliable ways to check for substring existence. It returns the index of the first occurrence of the specified substring, or -1 if the substring is not found.
const str = "Hello, world!";
const substring = "world";
if (str.indexOf(substring) !== -1) {
console.log("Substring found!");
} else {
console.log("Substring not found!");
}
This approach works because indexOf() returns the position (which is truthy) when found, and -1 (which is falsy) when not found. You can also use this in a more concise way:
const str = "JavaScript is awesome";
console.log(str.indexOf("is") > -1); // true
console.log(str.indexOf("not") > -1); // false
Atta Comsian explains that indexOf() returns the index of the first occurrence of a substring within a string, making it suitable for checking substring existence.
The search() Method
The search() method is similar to indexOf() but accepts a regular expression as an argument instead of a string. It returns the index of the match, or -1 if no match is found.
const str = "Hello, world!";
const substring = "world";
console.log(str.search(substring)); // 7
console.log(str.search(/world/)); // 7
console.log(str.search("goodbye")); // -1
The search() method is particularly useful when you need to perform pattern matching rather than simple substring search:
const str = "JavaScript is awesome";
console.log(str.search(/\s\w+\s/)); // 10 (finds the space around "is")
The match() Method
The match() method is used to find matches against a regular expression. It returns an array containing the matches, or null if no matches are found.
const str = "Hello, world!";
const substring = "world";
if (str.match(substring)) {
console.log("Substring found!");
console.log(str.match(substring)); // ["world"]
} else {
console.log("Substring not found!");
}
Sentry explains that match(searchValue) finds the searchValue (a regular expression) within a given string and returns an array containing the matches.
Performance Comparison
When performance matters, here’s how these methods compare:
| Method | Performance | Best For |
|---|---|---|
includes() |
Very fast | Modern browsers, simple substring checks |
indexOf() |
Very fast | Legacy browser support, need index position |
search() |
Slower | Regular expression pattern matching |
match() |
Slower | Complex pattern matching with captured groups |
According to Stack Abuse, indexOf() is suitable to be used as a polyfill for includes() and performs well for basic substring checks.
Browser Compatibility
- includes(): Not supported in Internet Explorer. For broader compatibility, you may need a polyfill.
- indexOf(): Supported in all browsers, including Internet Explorer 8+.
- search(): Supported in all browsers.
- match(): Supported in all browsers.
For maximum browser compatibility, especially when supporting older browsers like Internet Explorer, indexOf() is your best bet. If you’re working in a modern environment or can use transpilers, includes() is more readable.
Practical Examples
Basic Substring Check
function containsSubstring(str, sub) {
return str.includes(sub);
}
console.log(containsSubstring("JavaScript", "Script")); // true
console.log(containsSubstring("Hello", "World")); // false
Case-Insensitive Check
function containsCaseInsensitive(str, sub) {
return str.toLowerCase().includes(sub.toLowerCase());
}
console.log(containsCaseInsensitive("JavaScript", "script")); // true
console.log(containsCaseInsensitive("Hello World", "WORLD")); // true
Check Multiple Substrings
function containsAny(str, substrings) {
return substrings.some(sub => str.includes(sub));
}
console.log(containsAny("Hello world", ["hello", "world", "goodbye"])); // true
console.log(containsAny("Hello world", ["python", "java"])); // false
Check All Substrings
function containsAll(str, substrings) {
return substrings.every(sub => str.includes(sub));
}
console.log(containsAll("JavaScript is awesome", ["JavaScript", "awesome"])); // true
console.log(containsAll("JavaScript is awesome", ["JavaScript", "PHP"])); // false
Conclusion
JavaScript offers several effective methods to check if a string contains a substring:
- Use
includes()for modern, clean code when you only need a boolean result and don’t need browser compatibility for Internet Explorer - Use
indexOf()for maximum browser compatibility or when you need the actual position of the substring - Use
search()when you need regular expression pattern matching capabilities - Use
match()when you need to capture groups or perform complex pattern matching
The includes() method is generally preferred in modern JavaScript development for its clarity and readability, while indexOf() remains the most compatible option across all browsers.
Sources
- How to check whether a string contains a substring in JavaScript? - Stack Overflow
- How to Check Whether a String Contains a Substring in JavaScript? | Sentry
- Check for Substring in JavaScript - GeeksforGeeks
- Check if a string contains a substring using indexOf() in JavaScript - Atta Comsian
- How to Check Whether a String Contains a Substring in JavaScript - Tutorial Republic
- JavaScript: Check if String Contains a Substring - Stack Abuse
- How to Check If a String Contains a Substring in JavaScript - Bacancy Technology
- How to check if string contains substring in JavaScript – TecAdmin
- Check if a string contains a substring in JavaScript - 30 seconds of code
- How to Check if a String Contains a Substring in JavaScript - FreeCodeCamp