

The JavaScript includes() method, introduced in ES6, determines whether a string contains the characters you have passed into the method. In this tutorial, we’re going to discuss methods you can use to check if a JavaScript string contains another string using these three approaches. There are three methods for checking if a JavaScript string contains another character or sequence of characters: Access exclusive scholarships and prep coursesīy continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.Career Karma matches you with top tech bootcamps.These powerful new features will modernize your JavaScript with shorter and more expressive code. This guide will bring you up to speed with all the latest features added in ECMAScript 13. , 'book8' or 'book9'?Ĭonsole.log(/book(\d)/.test(str)) // falseġ1 Amazing New JavaScript Features in ES13 const str = 'Bread and Milk' Ĭonsole.log(/?and/.test(str)) // true Using regex matching allows us to easily specify complex patterns to search the string for. One way to do this is using the RegExp test() method. We can test the string against regex patterns to determine if it contains a substring. Str.toLowerCase().indexOf(substr.toLowerCase()) > -1 To perform a case-insensitive check, convert both the string and the substring to lowercase before calling indexOf() on the string. This is why we compare the result of indexOf() with -1 to check if the substring is in the string. If the value can’t be found, it returns -1. The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. For example: const str = 'Bread and Milk' Ĭonsole.log(str.indexOf(substr1) > -1) // trueĬonsole.log(str.indexOf(substr2) > -1) // false We call the indexOf() method on the string, passing the substring as an argument. We can also use the indexOf() method to check if a string contains a substring. Str.toLowerCase().includes(substr.toLowerCase()) To perform a case-insensitive check, convert both the string and the substring to lowercase before calling includes() on the string.
