How to check if a string contains a substring in JavaScript?
I’m looking for a method to determine if a string contains a specific substring. I expected a String.contains() method, but it doesn’t seem to exist in JavaScript. What are the standard approaches to check for substring presence in JavaScript strings?
How to Check if a String Contains a Substring in JavaScript
To check if a string contains a substring in JavaScript, you can use the includes()
method, indexOf()
, or regular expressions. The most straightforward approach is using string.includes(substring)
, which returns true
if the substring is found and false
otherwise.
Contents
- What methods exist to check for substring presence?
- How to use String.prototype.includes()?
- How to use String.prototype.indexOf()?
- What about regular expressions?
- How does String.prototype.search() work?
- Which method should you choose?
- Practical examples and use cases
What methods exist to check for substring presence?
JavaScript provides several ways to check if a string contains a substring. While there isn’t a String.contains()
method like in some other languages, there are several standard approaches:
String.prototype.includes()
(ES6)String.prototype.indexOf()
- Regular expressions with
RegExp.prototype.test()
String.prototype.search()
Each method has its own advantages and use cases. Let’s explore each one in detail.
How to use String.prototype.includes()?
The includes()
method is the most direct and readable way to check for substring presence in JavaScript. It was introduced in ES6 and is widely supported in modern browsers and Node.js.
const str = "Hello, world!";
const containsWorld = str.includes("world"); // true
const containsFoo = str.includes("foo"); // false
Key features of includes():
- Case-sensitive by default
- Returns a boolean (
true
orfalse
) - Accepts an optional second parameter for starting position
- More readable than other methods for simple substring checks
Here’s an example with the optional position parameter:
const str = "Hello, world!";
// Start searching from position 7
str.includes("world", 7); // true
str.includes("Hello", 7); // false
The includes()
method is the recommended approach for most use cases where you simply need to check if a substring exists within a string.
How to use String.prototype.indexOf()?
Before includes()
was introduced in ES6, indexOf()
was the standard way to check for substring presence. This method returns the index of the first occurrence of the specified substring, or -1 if the substring is not found.
const str = "Hello, world!";
const containsWorld = str.indexOf("world") !== -1; // true
const containsFoo = str.indexOf("foo") !== -1; // false
Key features of indexOf():
- Case-sensitive by default
- Returns the index position (or -1 if not found)
- Also accepts an optional second parameter for starting position
- Can be used to find the position of the substring, not just its presence
Here’s an example with the optional position parameter:
const str = "Hello, world!";
// Start searching from position 7
str.indexOf("world", 7); // 7
str.indexOf("Hello", 7); // -1
While indexOf()
works perfectly well for checking substring presence, includes()
is generally preferred for this specific task because it directly returns a boolean, making the code more readable.
What about regular expressions?
Regular expressions provide a powerful way to check for substring presence, especially when you need more complex pattern matching.
const str = "Hello, world!";
const regex = /world/;
containsWorld = regex.test(str); // true
containsFoo = /foo/.test(str); // false
Key features of regular expressions:
- Can match complex patterns, not just fixed strings
- Case-insensitive matching with the
i
flag - Supports global matching with the
g
flag - More powerful but also more complex to use
Here’s an example with case-insensitive matching:
const str = "Hello, World!";
const regex = /world/i; // 'i' flag for case-insensitive
regex.test(str); // true
Regular expressions are overkill for simple substring checks but become very useful when you need to match patterns rather than fixed strings.
How does String.prototype.search() work?
The search()
method is similar to indexOf()
but uses a regular expression as the search pattern instead of a string.
const str = "Hello, world!";
containsWorld = str.search(/world/) !== -1; // true
containsFoo = str.search(/foo/) !== -1; // false
Key features of search():
- Accepts a regular expression as the search pattern
- Returns the index of the match, or -1 if not found
- Similar to
indexOf()
but with regex support - Case-sensitive by default
Here’s an example with case-insensitive matching:
const str = "Hello, World!";
str.search(/world/i); // 7
The search()
method is useful when you need the position of a pattern match but don’t need the full power of match()
or need to extract the matched substring.
Which method should you choose?
The choice of method depends on your specific needs:
- For simple substring presence checks:
includes()
is the most readable and direct approach. - When you need the position of the substring:
indexOf()
is a good choice. - For complex pattern matching: Regular expressions with
test()
orsearch()
are necessary. - When working with older environments that don’t support ES6:
indexOf()
is the best option.
Here’s a performance comparison of the different methods:
Method | Returns | Case-sensitive | Position parameter | Performance |
---|---|---|---|---|
includes() |
Boolean | Yes | Yes | Good |
indexOf() |
Index/-1 | Yes | Yes | Excellent |
regex.test() |
Boolean | Configurable | No | Slower for simple strings |
search() |
Index/-1 | Configurable | No | Slower for simple strings |
For most modern JavaScript development, includes()
is the preferred method for checking substring presence due to its clarity and directness.
Practical examples and use cases
Here are some practical examples of checking for substring presence in JavaScript:
Basic substring check
const email = "user@example.com";
const isValidEmail = email.includes("@"); // Basic email validation
Case-insensitive check
const text = "Hello World";
const hasHello = text.toLowerCase().includes("hello"); // true
Checking for multiple substrings
const text = "JavaScript is versatile";
const checks = [
text.includes("Java"),
text.includes("script"),
text.includes("versatile")
];
// checks = [true, true, true]
Conditional logic with substring checks
const userInput = "I want to cancel my order";
if (userInput.includes("cancel")) {
// Handle cancellation
} else if (userInput.includes("modify")) {
// Handle modification
} else {
// Handle other cases
}
Checking with position parameter
const text = "The quick brown fox";
// Check if "fox" appears after position 10
const containsFoxAfterPosition = text.includes("fox", 10); // true
Combining with array methods
const texts = ["Apple", "Banana", "Cherry", "Date"];
const hasTextWithA = texts.some(text => text.includes("A")); // true
Validating input
function containsBadWords(input) {
const badWords = ["spam", "scam", "fake"];
return badWords.some(word => input.toLowerCase().includes(word));
}
const userInput = "This is not spam";
containsBadWords(userInput); // true
Conclusion
In JavaScript, there are several methods to check if a string contains a substring, each with its own advantages. The includes()
method introduced in ES6 is the most direct and readable approach for this task. For compatibility with older environments, indexOf()
remains a solid choice. Regular expressions offer powerful pattern matching capabilities when more complex matching is needed. By understanding these methods and their use cases, you can choose the most appropriate approach for your specific needs.