3 ways to check a substring in string in javascript

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

The indexOf method is a native javascript method implemented in ES6 that 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.

Complete example

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

search javascript method

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

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

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

ES6 includes a method

As part of the JavaScript language, 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.

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.