The JavaScript includes method on String allows you to check if a text is contained in a string. This method can also be applied to arrays, as we’ll see later in the tutorial.
The syntax of this method is therefore the following: string.includes(value, start).
Where string represents the string where to search for the value. The value parameter can be a word, a number, or a phrase. It does not matter how many times the value is contained in the string, in any case the important thing is to find it at least once.
Instead, the start parameter represents the starting point for carrying out the search, since in some cases it is preferable not to start from the beginning. If the start parameter is not specified, the default value is 0.
The method returns a Boolean value, that is, true or false.
Examples JavaScript includes on String
Now let’s do some simple examples of using the includes() method with strings.
Given a sentence contained in a string variable, check if a word is contained in this sentence.
In the example below, therefore, let’s try to search for the word thought within an example sentence. We use the JavaScript includes method for this purpose.
var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';
var includeString = coding.includes('thinking');
console.log(includeString);
In the browser console we will display the value true, as the word thought is contained in our example string.
Clearly, even more words can be searched, as long as they are contained in the exact order.
So even in the example below, the result is true.
var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';
var includeString = coding.includes('logical thinking');
console.log(includeString);
When the sequence is not correct, or not all the words are contained in the sentence then the result is false.
So here’s an example where the return value is false.
var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';
var includeString = coding.includes('the logical thinking');
console.log(includeString);
In this lesson we have done some examples of using JavaScript includes with string. This method can also be used with arrays and the lesson can be found at the following link: inlcudes with arrays.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts
JavaScript variables and costants
[…] Prev lesson: includesNext lesson: lastIndexOf […]