NeuroAgent

How to Check String Contains Substring in JavaScript

Learn multiple methods to check if a string contains a substring in JavaScript. includes(), indexOf(), search(), and match() with examples and performance comparison.

Question

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?

NeuroAgent

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 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.

javascript
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:

javascript
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.

javascript
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:

javascript
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.

javascript
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:

javascript
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.

javascript
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

javascript
function containsSubstring(str, sub) {
    return str.includes(sub);
}

console.log(containsSubstring("JavaScript", "Script")); // true
console.log(containsSubstring("Hello", "World")); // false

Case-Insensitive Check

javascript
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

javascript
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

javascript
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:

  1. Use includes() for modern, clean code when you only need a boolean result and don’t need browser compatibility for Internet Explorer
  2. Use indexOf() for maximum browser compatibility or when you need the actual position of the substring
  3. Use search() when you need regular expression pattern matching capabilities
  4. 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

  1. How to check whether a string contains a substring in JavaScript? - Stack Overflow
  2. How to Check Whether a String Contains a Substring in JavaScript? | Sentry
  3. Check for Substring in JavaScript - GeeksforGeeks
  4. Check if a string contains a substring using indexOf() in JavaScript - Atta Comsian
  5. How to Check Whether a String Contains a Substring in JavaScript - Tutorial Republic
  6. JavaScript: Check if String Contains a Substring - Stack Abuse
  7. How to Check If a String Contains a Substring in JavaScript - Bacancy Technology
  8. How to check if string contains substring in JavaScript – TecAdmin
  9. Check if a string contains a substring in JavaScript - 30 seconds of code
  10. How to Check if a String Contains a Substring in JavaScript - FreeCodeCamp