Return to Kroll Design home page

JavaScript Tutorials

 
« Return

JavaScript in action: Count how many times each letter of the alphabet occurs.

Type or paste any text into the text box, then click the Submit Query button. The form will pass your text to a PHP script which strips off any non-alphabetic characters, which in turn passes it to JavaScript code which counts how many times each letter of the alphabet occurs in your text.

Code for the form:

<form method="post" action="letter_counter2.php">
<textarea rows="20" cols="50" name="text_input"></textarea>
<input type="submit">
</form>

Code for the PHP and JavaScript:

<p class="hdr-notes">
Here are the number of times that each letter occurs:
</p>

<?php
$original_text = $_POST['text_input'];
$pattern = "/[^a-zA-Z]/";
$replacement = "";
$cleaned_up_text = preg_replace($pattern, $replacement, $original_text);
?>

<script type="text/javascript">

var textSource = "<?php echo($cleaned_up_text); ?>";

a_thru_z_string = "abcdefghijklmnopqrstuvwxyz";
a_thru_z_array  = a_thru_z_string.split("");

document.write("<table>");

for (i=0; i<26; i++) {
	regexPattern = eval("/" + a_thru_z_array[i] + "/gi");

	if (resultArray = textSource.match(regexPattern))
	{ letterCount = resultArray.length;
	  document.write("<tr>");

	  document.write("<td align='left'>");
	  document.write(a_thru_z_array[i], ":");
	  document.write("</td>");

	  document.write("<td align='right'>");
	  document.write(letterCount);
	  document.write("</td>");

	  document.write("</tr>");
  }
}
document.write("</table>");
</script>


 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM