How to check if the String contains the Substring in Javascript?
Contents
String Includes method in Javascript
Includes( ) is one of the String method in Javascript. It is used to checks whether a string contains the specified string/characters and returns true or false based on matching.
Syntax of includes method in Js
1 |
string.includes(searchString, position) |
- searchString – A string to be searched for within str.
- position – The position within the string at which to begin searching for searchString. (Defaults to 0.)
- Return value – true if the search string is found anywhere within the given string; otherwise, false if not.
Example for Includes method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// JavaScript to demonstrate includes() function <script> function searchString() { // Original string var inputString = 'revisit class'; // Check the substring value in the inputString var subString= 'revisit'; console.log(inputString.includes(subString)); } searchString(); </script> |
As mentioned in code, the input String value is “revisit class” and the substring value that we want to search is “revisit”. To check whether the string contains the substring or not, we have used includes method like “inputString.includes(subString)“.
This method will return the true if the Input string contains the sub string value. Otherwise it will return false.
Output:
1 |
true |
Use case : Check the email service provider using includes method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html lang="en"> <head> <style> .button{ background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; cursor: pointer; } </style> <title>Document</title> <script type="text/javascript"> function searchText(){ // Get the input from the text box const string = document.getElementById("ip1").value; const substring = document.getElementById("ip2").value; //validate the given string contains the sub string and print the result var x = document.createElement("div"); if(string.includes(substring)){ x.textContent = "Revisit Class is using Gmail"; //true document.body.appendChild(x); } else{ x.textContent = "Revisit Class is not using Gmail"; //false document.body.appendChild(x); } } </script> </head> <body> <h1> String Contains Substring example in Javascript</h1> Email Address:<input type="text" id="ip1"><br><br> Service Provider:<input type="text" id="ip2"><br><br> <button class="button" onclick="searchText()">Submit</button><br> </body> </html> |
Output
Recommended Articles