3 ways to check a substring in string in javascript with examples

This post covers different ways of checking a given string exists in a given input.

In javascript, There are many ways to check with substring check for a given input string.

  • ES6 Include
  • ECMAScript5 indexOf
  • ES5 search method

ECMAScript5 indexOf method to check substring

The indexOf method is a native javascript method introduced in ES6. It returns the position of a substring matched in a given string, or -1 if none is found.

Here is an example

const input = "cloudhadoop";
const string = "cloud";
const string1 = "welcome";

console.log(input.indexOf(string)); //returns 0
console.log(input.indexOf(string1)); // returns -1

To check a given substring found in a string using if statements

Complete example

if (input.indexOf("string") >= 0) {
  console.log("substring found in a given input");
}

search javascript method to find substring

Search is an inbuilt method in javascript. It returns the position of a string in a given input string, takes a string or a regular expression as a parameter, and returns the element’s location, or 01 if no element was found.

const string = "Hello Cloud";
const result = string.search("Cloud");
console.log(result);

search and indexOf do not check for the case-sensitive string.

ES6 includes a method to check substring

As part of the JavaScript language improvement, the includes method was implemented in the ES6 alias ECMAScript 6 version. It uses a string parameter that is compared to the input string.

It returns true or false Boolean values.

Here’s a comprehensive example.

const input = "cloudhadoop";
const string = "cloud";
const string1 = "welcome";

console.log(input.includes(string)); // true
console.log(input.includes(string1)); // false

The only disadvantage is this method supports the IE11 browser. You can write a polyfill for this.