JavaScript - String includes() method
In this post, we will discuss about string includes() method in JavaScript. includes() is a method used to find the given sub-string is present in the parent string.
Let us create the String for demonstration.
Copied
let string1=' I like the JavaScript and JavaScript is popular and easy learn and gets job easily with JavaScript skill.';
console.log(string1);
Output:
I like the JavaScript and JavaScript is popular and easy learn and gets job easily with JavaScript skill.
String includes() :
includes() method used to find the given sub-string is present in the parent string.
includes() syntax:
String. includes('sub-string')
Where 'sub-string' is the given string to check whether parent contains this sub-string. If its present this includes() method will returns 'true' otherwise 'false'.
includes() example 1:
create a string declaration with sentence and find whether given sub-string is present in the parent string.
Copied
let str='I like the JavaScript and JavaScript is popular and easy learn and gets job easily with JavaScript skill.';
console.log('parent string = '+str);
let substring = 'JavaScript';
console.log('parent string contains JavaScript? '+str.includes(substring));
Execution Steps:
- Copy the above example code.
- Open the browser(chrome or Microsoft edge) and press(ctrl+shift+I).
- Go to the console tab.
- Paste the copied code into console and press enter button.
Output:
parent string = I like the JavaScript and JavaScript is popular and easy learn and gets job easily with JavaScript skill.
parent string contains JavaScript? true
includes() example 2:
In this example, we will explore includes() method by passing the non-existent sub-string and log the output to the console.
Copied
let str='student who gets first marks that student will be eligible for scholarship';
console.log('Given String = '+str);
let substring = 'students';
console.log('parent string contains students? '+str.includes(substring));
Execution Steps:
- Copy the above example code.
- Open the browser(chrome or Microsoft edge) and press(ctrl+shift+I).
- Go to the console tab.
- Paste the copied code into console and press enter button.
Output:
Given String = student who gets first marks that student will be eligible for scholarship
parent string contains students? False