

The JavaScript includes() method was introduced with ES6, and it is the most common and modern way of checking if a string contains a specific character or a series of characters. What Is The includes() Method in JavaScript? includes() Method Syntax Breakdown How to make a case-insensitive check with the includes() and indexOf() methods.How to check if a string contains a specific substring using the indexOf() method.Syntax breakdown of the indexOf() method in JavaScript.How to check if a string contains a specific substring using the includes() method.Syntax breakdown of the includes() method in JavaScript.Here is what we will cover in more detail: How to use the built-in indexOf() JavaScript method.How to use the built-in includes() JavaScript method.In this article, you will learn two different ways you can check if a string contains a substring using JavaScript methods. Thankfully, there are a few quick ways to achieve this with JavaScript. Specifically, you might need to check whether a word contains a specific character or a specific set of characters. A substring is a string inside another string. Let's try it out.When you're working with a JavaScript program, you might need to check whether a string contains a substring. 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. Looking through the documentation for String.prototype, the search method looks promising due to its name. 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 )
