DEV Community

Cover image for String.includes() in JavaScript
Moazam Ali
Moazam Ali

Posted on

String.includes() in JavaScript

The String.prototype.includes() method is a string method in JavaScript that returns a Boolean value indicating whether a string includes a specified search string. This method is case-sensitive, meaning that it will return true only if the search string exactly matches a substring of the target string.

Syntax

string.includes(searchValue, start)
Enter fullscreen mode Exit fullscreen mode
  • searchValue: A specified search string to be searched for within a string.
  • start: The position within the string at which to begin searching for searchString. (Defaults to 0.)

It returns a boolean value, true if the searched string is found within the given string; otherwise false if not found.

Here's an example of how to use the includes() method:

let str = 'Hello, world!';

console.log(str.includes('Hello')); // Output: true
console.log(str.includes('hello')); // Output: false
Enter fullscreen mode Exit fullscreen mode

In this example, we create a string called str and use the includes() method to search for the substring 'Hello' within it. Since the search string exactly matches the substring 'Hello', the includes() method returns true. However, if we search for the string 'hello', which is not an exact match, the includes() method returns false.

The includes() method also accepts an optional second argument, which is the index at which the search should start. This is useful if you want to search for a substring within a specific part of the target string.

Here's an example of using the optional second argument:

let str = 'Hello, world!';

console.log(str.includes('world', 6)); // Output: true
Enter fullscreen mode Exit fullscreen mode

In this example, we search for the substring 'world' within the string str, starting at the index 6. Since the string 'world' appears at index 7, the includes() method returns true.

Wrapping up!

The includes() method is a convenient and easy way to search for substrings within a string in JavaScript. It's often used in combination with other string methods, such as indexOf() and substr(), to perform more complex string operations.

That's all for this article, hope you learned something. Thanks for reading, catch you later.

You can also buy me a coffee that would help me grow as a frontend developer :)

Buy Me A Coffee


Top comments (0)