/

Exploring the JavaScript includes() Method

Exploring the JavaScript includes() Method

In JavaScript, the includes() method can be used to determine whether a string contains a specific value as a substring. The method returns a boolean value, true if the string includes the specified value, and false otherwise.

Here are a few examples to illustrate its usage:

1
2
3
4
5
'JavaScript'.includes('Script') // true
'JavaScript'.includes('script') // false
'JavaScript'.includes('JavaScript') // true
'JavaScript'.includes('aSc') // true
'JavaScript'.includes('C++') // false

In the first example, 'JavaScript' contains the substring 'Script', so the includes() method returns true. However, it is case-sensitive, so in the second example, 'script' is not found within the string 'JavaScript', resulting in false.

Furthermore, the includes() method also has an optional second parameter, which specifies the position from where the search should begin. Here’s an example:

1
2
3
'a nice string'.includes('nice') // true
'a nice string'.includes('nice', 3) // false
'a nice string'.includes('nice', 2) // true

In the first example, 'nice' is found in the string 'a nice string', resulting in true. However, in the second example, the search starts from the position 3, which means it skips the occurrence of 'nice' and returns false. Finally, in the third example, the search starts from position 2, and 'nice' is found, returning true.

By utilizing the includes() method, you can easily check whether a string includes a specific substring. Remember to pay attention to case-sensitivity and explore the optional second parameter for advanced searching.

tags: [“JavaScript”, “string”, “includes method”]