

IndexOf does a case-sensitive search on the string. var string = "foo" var substring = "oo" console.log(string.indexOf(substring) != -1) // true It is often used in arrays, and the same can be applied with strings. The indexOf method would return -1 if the substring is not present in the string.

IndexOf can be used to decide if the string, contains a substring or not. This means, you must have a fallback mechanism in your code to handle these environments.

Older browsers, and especially Internet Explorer does not support. Includes does a case-sensitive search on the string.Īs developers, you need to be watchful off when the includes is being used. ‘amtrack’.If you are using the most recent version of JavaScript, for development, you have the liberty of using the includes function in the String Prototype.ĮCMAScript 6 introduced const string = "foo" const substring = "oo" console.log(string.includes(substring)) // true ‘amtrack’.indexOf(‘a’) // 0 – Javascript string contains character check Read: How to remove a property from a Javascript Object You can also pass an optional second parameter to indicate where to start searching. This method returns an integer with the position of the substring, and if it does not find the substring, it returns -1. ‘AMTRACK’.includes(‘M’, 1) // true Using the indexOf () methodīefore the release of the official method includes(), another way to check if a string contains a substring was to use the method indexOf(). You can optionally pass a second parameter to indicate where to start looking for the substring: Read: How to delete values from an array in Javascript ‘HI WORLD’.toLowerCase().includes(‘world’) // true – javascript string lowercase

Note that the method includes()is case sensitive, so if you want to search for an independent string if it is uppercase or lowercase, you can do the following: ‘Hi world’.includes(‘world’) // true – javascript includes string method The method includes()is the official way to check if a string is contained within another string. In JavaScript there are several ways to check whether a string contains a word or a substring. Checking if a string contains a word is a common task in any programming language.
