How To Count SubString Occurrence In A String Using 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