Javascript Proper Title Case Code Snipit
30 November -0001
This little bit of code translates information in the input box into proper title case. Special thanks to Thomas Gabriel for pointing out that the earlier version used the JavaScript function indexOf() which is not supported in Internet Explorer.
Demo:
Code:
<html> <head> <script type="text/javascript"> /* Function coded by and copyright Justin C. Klein Keane This function will grab the value of the field named 'theField' in the form named 'theForm' and step through it, resetting the first word with proper capitalization and any other word not found in the special_words array. to use code you submit button with '<input type="submit" onClick="fixit()"/>' Any questions or comments: justin@madirish.net */ //this probably isn't a complete list of words that shouldn't be capitalized var special_words = new Array('and', 'the', 'to', 'for', 'is', 'in', 'a', 'at', 'an', 'from', 'by', 'if', 'of'); function ie_has_no_indexOf(input) { for (var i=0;i<special_words.length;i++) { if (special_words[i]==input) { return 1; } } return -1; } function fixit() { var original = document.theForm.theField.value; var o_split = original.split(" "); for (i=0;i<o_split.length;i++) { if (i == 0) { //always capitalize the first word o_split[i] = (o_split[i].substring(0,1)).toUpperCase() + o_split[i].substring(1); } else if(ie_has_no_indexOf(o_split[i]) < 0) { o_split[i] = (o_split[i].substring(0,1)).toUpperCase() + o_split[i].substring(1); } } retval = o_split.join(' '); document.theForm.theField.value = retval; } </script> </head> <body> <form name="theForm"> <input type="text" name="theField" size="50"><br> <input type="button" onClick="fixit()" value="fix it!"><input type="reset"> </body> </html>