The includes() method is a built-in method in JavaScript that determines whether a string or array contains a specified value. It is a versatile and commonly used method for searching within strings and arrays. The includes() method is case-sensitive, meaning it distinguishes between uppercase and lowercase characters.
In this example, includes() checks if the substring 'Hello' is present in the string 'Hello, World!'. Since it is, the method returns true.
let str = 'Hello, World!'; let substring = 'Hello'; console.log(str.includes(substring)); // Output: true
Check Array for Element:
includes() can be used with arrays to check if a specific element is present.
let array = [1, 2, 3, 4, 5]; let element = 3; console.log(array.includes(element)); // Output: true
Check for Multiple Substrings
You can use a loop to check for the presence of multiple substrings in a string.
let str = 'JavaScript is a powerful language'; let substrings = ['JavaScript', 'Python', 'language']; for (let substring of substrings) { console.log(str.includes(substring)); } // Output: true, false, true
Complex Example with Objects
In this complex example, the includes() method is not directly applicable because it performs reference-based comparison. Instead, we use the some() method along with JSON.stringify() to compare objects in the array with the search object.
const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; const searchUser = { id: 2, name: 'Bob' }; //Note that we are using some instead of includes here const result = users.some(user => JSON.stringify(user) === JSON.stringify(searchUser)); console.log(result); // Output: true