Skip to content

Instantly share code, notes, and snippets.

@MOgorodnik
Created December 1, 2015 09:21
Show Gist options
  • Save MOgorodnik/a91a29a7644503c69d19 to your computer and use it in GitHub Desktop.
Save MOgorodnik/a91a29a7644503c69d19 to your computer and use it in GitHub Desktop.
JavaScript Strings: Uppercase, Lowercase and Capitalization
// uppercase
var sourceText = "To see a World in a Grain of Sand";
console.log(sourceText.toUpperCase());
> TO SEE A WORLD IN A GRAIN OF SAND
// lowercase
var sourceText = "And a Heaven in a Wild Flower";
sourceText = sourceText.toLowerCase();
console.log(sourceText);
> and a heaven in a wild flower
// Capitalisation >>> h1 { text-transform: capitalize; }
// This is the broadest function, correctly transforming letters with diacritics and characters after hyphens.
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ź
// Capitalising the first letter of the first word >>> p:first-letter { text-transform: uppercase; }
String.prototype.toSentenceCase = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
var auguries = "hold infinity in the palm of your hand";
console.log(auguries.toSentenceCase());
> Hold infinity in the palm of your hand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment