3 ways to check a substring in string in javascript

This post covers different ways of checking given string exists in an 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, 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 does not check for case sensitive string.

ES6 includes method

As part of the JavaScript language, the includes method was implemented in 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

Only disadvantage is this method not supports in 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.