Skip to content

JavaScript includes method | Array and String example

  • by

JavaScript includes() method work with Array and String. Where it used with String to determines whether a string contains the characters of a specified string. And in Array determines whether an array contains a specified element.

Examples of JavaScript includes

Let’s the example of includes() method with Array and Strings.

JavaScript array includes an example

array.includes(element, start)

check if an array includes “A”:

<!DOCTYPE html>
<html>
  <head>
    <script>
 
    	var alpha = ["B", "A", "C", "D"];
	var n = alpha.includes("A");
        alert(n)
 
    </script>
  </head>   
 
</html>

Output:

JavaScript includes method

Read more:- Array includes method | check if a value exists

JavaScript string includes an example

Code snippet

string.includes(searchvalue, start)

Let’s see if a string includes “world” word.

<!DOCTYPE html>
<html>
  <head>
    <script>
 
    	var str = "Hello world, welcome to the EyeHunts.com";
	var n = str.includes("world");
        alert(n)
 
    </script>
  </head>   
 
</html>

Output:

JavaScript includes method example

Read more:- String includes method | Search one string into another string

Q: How to javascript includes() case insensitive can work?

Answer: You can try this, Add .toLowerCase() after referrer. This method turns the string in a lower case string.

str = "Wow its so COOL"
searchStr = "CoOl"

console.log(str.toLowerCase().includes(searchStr.toLowerCase()))

Q: JavaScript includes not working in All browsers.

Answer: If you look at the documentation of includes(), most of the browsers don’t support this property.

You can use widely supported indexOf() after converting the property to string using toString():

Read this:- Javascript indexof Method | Search specified item/string in the Array/String

Do comment if you have any doubts and suggestion on this article.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading