![]() If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like Unlimited arguments in a JavaScript function in 2 ways. The general syntax for the includes () method looks something similar to this: string. The includes() method provides cleaner code, but indexOf() returns information that includes() doesn’t. 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. In the example above we can see the application of both methods. NOTE: includes() is not supported in Internet Explorer.Ĭonsole.log("A substring is close enough") This returns a boolean value indicating whether the search element or string is present in the array or string. If not specified, the search begins at index 0. position (optional) This is the index from which the search begins. Also, includes() accepts the same two parameters as indexOf(). searchString This is the string that the function searches for. Instead of returning index, includes() method returns true or false. () and () are present in ES5 edition of ECMAScript and hence supported by all browsers. ![]() With regards to browser support, use them wisely. ![]() The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate, according to MDN. () was introduced in ECMAScript 2015 whereas () was introduced in ECMAScript 2016. Check if JavaScript string contains a substring ES6Īmong other things, ES6 introduced includes() method. This concludes pre-ES6 way of checking if JavaScript String contains substring. That means that there was no occurrence of our string after the index we’ve provided. But, when we used indexOf() with the second parameter that is larger than 8, -1 was returned. This means that the first occurrence of our string is on the 8th index. As we can see from the example above when we used indexOf() without the second parameter indexOf() returned 8.
0 Comments
Leave a Reply. |