


The code example below shows how you can use the indexOf method to check if a string contains a substring in ECMAScript 5 or older. } Option 2: Use the indexOf Method (ECMAScript 5 or older) run this code if People is present in the str constant const str = 'We the People of the United States, in Order to form a more perfect Union.' Ĭonsole.log(str.includes('We the')) // trueĬonsole.log(str.includes('Order')) // trueĬonsole.log(str.includes('notpresent')) // falseĬonsole.log(str.includes('WE THE')) // false The code snippet below shows you how to use the includes method to check if a string contains a substring in ECMAScript 6. Option 1: Use the includes Method (ECMAScript 6) One of the ways is done using the includes method for JavaScript 6 (ECMAScript 6) and the other is with the indexOf for JavaScript 5 (ECMAScript 5) or older. Let's try it out.There are two simple ways to check if a string contains a substring in JavaScript. RegExp.prototype has a test method which returns a boolean. However, that does point us toward something else useful. Unfortunately, with the exception of matching on a regular expression rather than a string, the behavior is identical to indexOf. To check if a string contains a substring in JavaScript, you can use the includes() method of the String object. One of the most basic tasks in any programming language is determining whether a string contains a given substring. Looking through the documentation for String.prototype, the search method looks promising due to its name. To check whether a string contains a substring in JavaScript, we can use the built-in method. Ideally, what we're looking for is a method with a name that matches our intention (determining if x contains y), and returns a simple true or false. That means that we can use it, but the clarity of the code suffers. In the event that no match is found, it will return -1. Its job is to return the index at which a given substring is found. While indexOf is often recommended as a simple way to test for the presence of a substring, that's not really its purpose.

Var philosophers = "Aquinas, Maimonedes, and Avicenna" var me = "Joshua" function printPhilosopherStatus ( person ) // Outputs: "Joshua is NOT a philosopher." printPhilosopherStatus ( me )
