Skip to content

Instantly share code, notes, and snippets.

Created Sep 26, 2010
What would you like to do?
// A javascript port of my Perl string capitaliser. Possibly someone who is better at
// DOM scripting than me could make a script that would automatically apply this to any
// element styled with text-transform: uppercase.
// Again, the algorithm is too simple to be worth insisting on attribution, but if you
// do use this script anywhere, please attribute it to me in a comment block somewhere.
// By David Kendal,
// see also the original perl version at
function is_exception (word, exceptions) { // possibly there's a routine built-in to JavaScript to do this
word = word.toLowerCase();
for (var i in exceptions) {
exception = exceptions[i].toLowerCase();
if (exception == word) {
return true;
return false;
function uppercase (text) {
exceptions = ["macbook", "wifi", "airport", "postscript"]; // if you have any more suggestions, mail them to me at the address ona
words = text.split(/\b/);
capitalised = "";
for (var i in words) {
word = words[i];
if (matches = word.match(/^(.{0,4})([A-Z].*)$/)) { // sadly javascript doesn't do POSIX character classes.
if (is_exception(word, exceptions)) {
matches[1] = matches[1].toUpperCase();
capitalised = capitalised + matches[1] + matches[2].toUpperCase();
} else {
capitalised = capitalised + word.toUpperCase();
return capitalised;
document.write(uppercase('I really love connecting my iPod to my MacBook and syncing with iTunes.'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment