How to check whether a string contains a sub string in javascript

       If you want to check whether a string contains substring or not in javascript we can make use of various functions available. In most of the below cases the methods return either -1 or false if the given substring is not available in the main string.

Check whether a string contains a substring or not in javascript
Different ways to find substring in a string in javascript:
1.Regexp
2.Match
3.Search
4.Includes
5.Indexof

Using RegExp
A regular expression is an object that describes a pattern of characters.Regular expressions are used to perform pattern-matching and “search-and-replace” functions on text. Test() method returns true if a match is found else it returns false.

<script>
function findSubstring() {
    var str = "check for sub string in a string in javascript";
    var pattern = new RegExp("e");
    var res = pattern.test(str);
    alert(res);
}
</script>

   In this case as ‘e’ is present in the main string ‘str’, the method test returns true.

Using Match
The match() method searches a string for a match against a regular expression. It returns the matches as an Array object.

<script>
function findSubstring() {
    var str = "check for sub string in a string in javascript"; 
    var res = str.match(/ing/g);
    alert(res);
}
</script>

   As match method returns an array of objects, g stands for the global search. If you want to perform a case-insensitive match you can include gi in place of g.




Using Search
Search method returns the position where the substring is found. It returns -1 if there is no match found. The search value can be a string or regular expression.

<script>
function findSubstring() {
    var str = "check for sub string in a string in javascript"; 
    var res = str.search("string");
    alert(res);
}
</script>

   As the substring ‘string’ is present in the given string ‘str’, search methods returns it’s position. Suppose the search string is given as ‘Python’ as it is not present in the main string, the Search method returns -1.

Using includes
The Includes checks for the occurrence of a substring in a string. If it is found it returns true. If not it returns false.

<script>
function findSubstring() {
    var str = "Hello welcome to ToPoint tutorial";
     var res = str.includes("welcome");
    alert(res);
}
</script>

   The given substring ‘welcome’ is present in the main string ‘str’. Hence, the method include returns true.

Using indexOf
The index of method returns the first occurrence of a given string if it is present in the string. If the specified value is not found in string then it returns -1.

<script>
function findSubstring() {
    var str = "Hello welcome to ToPoint tutorial";
    var n = str.indexOf("welcome");
    alert(n);
}
</script>

   In the above example, as substring ‘welcome’ is present in the main string, the method indexOf returns the first occurrence.
More Content : ToPoint
More about javascript : Learn more