Javascript String Occurrence In A String

How To Count SubString Occurrence In A String Using Javascript 

String Count Occurrence Inside A String Using Javascript


In this Javascript tutorial, we will learn how to count the number of occurrences of a specific string within a text using the substring() function and a for loop in Javascript
We will also use the NetBeans editor for coding.



Project Source Code:

    
<!DOCTYPE html>
<html>
    <head>
        <title>Javascript: string occurrence</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>js stringjs occurjsrence in a jsstring</p>
        <script>
            
            var txt = "js stringjs occurjsrence in a jsstring",
                valToFind = "string",
                count = 0;
            
            for(var i = 0; i < txt.length; i++){
                
                console.log(txt.substring(i, i+valToFind.length));
                //              (start, end)
                if(txt.substring(i, i+valToFind.length) === valToFind){
                    count++;
                }
                
            }
            console.log(count);
        </script>
        
        
    </body>
</html>




OUTPUT: 2

Share this

Related Posts

Previous
Next Post »