I wrote a simple JavaScript SEO keyword counter. The user enters their SEO keyword in one field then enters their webpage text in a textarea field. It then calculates (in realtime, as the user types) how many times the keyword appears in the web page text. It also calculates the keyword density.
It works but probably is more complicated than it needs to be.
My code is as follows:
function myFunction() {
var numberOfTimesKeyword = 0;
// Prep the text ////////////////////////////////////
// Remove all characters but a-z AND 0-9 AND spaces
var pageText = textarea.value.replace(/[^\w\s]/gi, '');
// Remove double spaces
pageText = pageText.replace(/\s\s+/g, ' ');
// Trim beginning and ending spaces
pageText = pageText.trim();
// End: Prep the text ////////////////////////////////////
// Make textarea values into array
var pageTextArray = pageText.split(" ");
// Go through array and find out how many times the keyword appears
for(var i in pageTextArray) {
if (pageTextArray[i] == textfield.value) {
numberOfTimesKeyword++;
}
}
// Find keyword density
var keywordDensity = (numberOfTimesKeyword / pageTextArray.length) * 100;
if (numberOfTimesKeyword > 0) { // The keyword appears at least once
containsText.innerHTML = "The keyword appears <strong>" + numberOfTimesKeyword + "</strong> time(s).";
} else {
containsText.innerHTML = "<strong>Does not contain keyword.</strong>";
}
densityText.innerHTML = "<strong>Keyword Density ((# of times keyword appears / total words) * 100):</strong> " + Math.ceil(keywordDensity) + "%";
lengthText.innerHTML = "<strong>Array Length:</strong> " + pageTextArray.length;
}
<p>
<strong>SEO Keyword:</strong>
<br>
<input type="text" name="textfield" id="textfield" oninput="myFunction()">
</p>
<p>
<strong>Webpage Text:</strong>
<br>
<textarea name="textarea" cols="20" rows="5" id="textarea" oninput="myFunction()"></textarea>
</p>
<hr>
<p>
<span id="containsText"><strong>Does not contain keyword.</strong></span>
<br>
<span id="densityText"><strong>Keyword Density ((# of times keyword appears / total words) * 100):</strong> ---</span>
<br>
<span id="lengthText"><strong>Array Length:</strong> ---</span>
</p>