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 *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…
How To

How to configure Git proxy?

If you are working in the corporate company all the internet requests usually goes through the corporate firewall.…