How to check if string contains another substring

The easiest way to check if the string contains another substring is by using indexOf() Javascript method.

The indexOf() method returns the position of the first occurrence of the specified value in a string. If the specified value is not found in the string then indexOf() returns -1.

To Check the substring position in the string using Javascript substring use the below code

var str = "Hello world, welcome to Javascript Coding.";
var n = str.indexOf("welcome");

//Returns 13

To check if string contains another substring

var s = "foo";
console.log(s.indexOf("oo") > -1)

//returns true

Browsers Supported:

  • IE
  • Firefox
  • Chrome
  • Safari

Another easiest way to achieve the same functionality is by using string.includes which have been added in the latest version of ES6.

Syntax for string.includes

var contained = str.includes(searchString [, position]);

Example of string.includes

var str = "Hello World, Welcome to Javascript Coding";

console.log(str.includes("Welcome to"));    // true
console.log(str.includes("Javascript")); // true
console.log(str.includes("To be", 1)); // false

*Note: This may require ES6 shim in older browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like