JavaScript's simplest text manipulations transform strings between uppercase and lowercase. Capitalization is trickier (and not yet an established method), but entirely achievable.
In many cases, you actually don’t need to use JavaScript for these processes: if the content is only going to be presented on a web page, it’s easier and more performant to transform text using CSS.
However, CSS has its limits: it can only be used to style the presentation of text context on the web page - paragraphs & headings, links, etc - and can’t influence text in attribute values, such as title
or alt
. If you’re trying to format text before it is inserted into a database, for example, JavaScript (possibly in combination with PHP and HTML5’s autocapitalize
attribute) is the way to go.
Uppercase
In JavaScript:
var sourceText = "To see a World in a Grain of Sand";
console.log(sourceText.toUpperCase());
> TO SEE A WORLD IN A GRAIN OF SAND
CSS Alternative: If the text was within an element with an id
of auguries1
:
#auguries1 { text-transform: uppercase; }
Lowercase
In JavaScript, use the very ironically camelCased toLowerCase()
method, shown here using slightly different code from the first example:
var sourceText = "And a Heaven in a Wild Flower";
sourceText = sourceText.toLowerCase();
console.log(sourceText);
> and a heaven in a wild flower
CSS Alternative: If the text was displayed in an element with a class
of auguries2
:
.auguries2 { text-transform: lowercase; }
Capitalisation
Title Case: Capitalize The First Letter Of Every Word
This is best left to a JavaScript function:
function toTitleCase(str) {
return str.replace(/[^-'\s]+/g, function(word) {
return word.replace(/^./, function(first) {
return first.toUpperCase();
});
});
}
var concertTitle = "live-alive in łódź";
console.log(toTitleCase(concertTitle));
> Live-Alive In Łódź
In CSS: to capitalize the first letter of every word in all h1
elements:
h1 { text-transform: capitalize; }
Sentence Case: Capitalising the first letter of the first word
So commonly needed that it is probably best to attach it to the string prototype, creating a new method:
String.prototype.toSentenceCase = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
To demonstrate it in the console:
var auguries = "hold infinity in the palm of your hand";
console.log(auguries.toSentenceCase());
> Hold infinity in the palm of your hand
In CSS: use a combination of selectors; for example, to capitalize the first letter in every paragraph:
p:first-letter { text-transform: uppercase; }
Lines of poetry are from William Blake’s Auguries of Innocence, sentence case technique derived from code by Steven Harrison.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.