Sling Academy
Home/JavaScript/JavaScript: Check if a string contains a substring (4 approaches)

JavaScript: Check if a string contains a substring (4 approaches)

Last updated: February 19, 2023

This practical article walks you through 4 different ways to check whether a given string contains a substring or not. Without any further ado (like talking about the history of Javascript or explaining what a string is), let’s get started.

Using regular expression

Regular expressions, or regex for short, is a powerful tool for checking if a string contains a substring in Javascript. You can flexibly choose between case-sensitive (default) or case-insensitive. Let’s take a look at the following example for more clarity:

// define a function for reusability
const check = (str, subStr, caseSensitive = false) => {
  if (caseSensitive) {
    return new RegExp(subStr).test(str);
  }
  return new RegExp(subStr, 'i').test(str);
}

// try the function
console.log(check('abc def ghi', 'abc')); // true
console.log(check('abc def ghi', 'ABC')); // false
console.log(check('abc def ghi', 'ABC', false)); // true

Compared to the next 2 solutions, this one is a bit longer, but it is the only solution that allows us to check with case insensitive.

Using the includes() method

The syntax for using the includes() method is as follows:

string.includes(substring);

The includes() method returns true if a string contains another string. Otherwise, it returns false. It’s important to note that this method is case-sensitive.

Example:

const str = 'Hello World';
const subStr1 = 'World';
const subStr2 = 'Worlds';

console.log(str.includes(subStr1)); // true
console.log(str.includes(subStr2)); // false

Using the indexOf() method

The syntax:

string.indexOf(substring)

The indexOf() method will return the position of the first occurrence of the substring in the string or -1 if the substring is not found. Similar to the includes() method, the indexOf() method is also case-sensitive.

If you are looking to find the position of a substring within a string, the indexOf() method is a great choice as well.

Example:

const str = "Sling Academy";
const subStr1 = "Academy";
const subStr2 = "Slug";

console.log(str.indexOf(subStr1) !== -1); // true
console.log(str.indexOf(subStr2) !== -1); // false

Using a for loop

We can do lots of things with the classic for loop. The example below shows you how to use it to check if a string contains a substring or not:

const check = (str, subStr) => {
  for (let i = 0; i < str.length; i++) {
    if (str[i] === subStr[0]) {
      for (let j = 1; j < subStr.length; j++) {
        if (str[i + j] !== subStr[j]) {
          break;
        }
        if (j === subStr.length - 1) {
          return true;
        }
      }
    }
  }
  return false;
};

console.log(check('hello', 'll')); // true
console.log(check('hello', 'oo')); // false

Although it also gives the correct answer, this approach is unnecessarily verbose. However, it is still useful for your reference purposes.

Next Article: 3 Ways to Reverse a String in JavaScript

Previous Article: JavaScript: Regular Expressions Cheat Sheet

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration