Skip to content

Instantly share code, notes, and snippets.



Last active Aug 7, 2019
What would you like to do?
String title case function for Deno


Usage example:

import { titleCase } from "";

console.log(titleCase("deno is AWESOME"));
console.log(titleCase("words-can contain_punctuation"));
console.log(titleCase("  spacing is     preserved"));


Deno Is Awesome
Words-can Contain_punctuation
  Spacing Is     Preserved

Run tests:

$ deno
running 4 tests
OK     titleCaseWorksWithAscii (0.00ms)
OK     titleCaseWorksWithUnicode (0.00ms)
OK     titleCasePreservesSpaces (0.00ms)
OK     titleCaseTreatsPunctuationAsLetters (0.00ms)
OK     titleCaseWorksWithEmoji (0.00ms)

test result: OK. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out (2.00ms)
* Convert a string to title case, i.e. the initial letter of each word is capitalised
* and all other letters lowercased. The only word boundary that counts is whitespace,
* and whitespace is preserved as-is.
export function titleCase(input: string): string {
return input.replace(/([^\s])([^\s]*)/g, replaceWord);
function replaceWord(match: string, initial: string, trailing: string): string {
return initial.toUpperCase() + trailing.toLowerCase();
import { test, runTests } from "";
import { assertEquals } from "";
import { titleCase } from "./title_case.ts";
test(function titleCaseWorksWithAscii() {
assertEquals(titleCase("hello world"), "Hello World");
assertEquals(titleCase("HELLO WORLD"), "Hello World");
assertEquals(titleCase("HeLlO wOrLd"), "Hello World");
test(function titleCaseWorksWithUnicode() {
assertEquals(titleCase("çoban ırmak"), "Çoban Irmak");
assertEquals(titleCase("çobanIrmak"), "Çobanirmak"); // capital I becomes lowercase i, of course
test(function titleCasePreservesSpaces() {
assertEquals(titleCase(""), "");
assertEquals(titleCase(" "), " ");
assertEquals(titleCase(" hello World"), " Hello World");
assertEquals(titleCase(" hello world "), " Hello World ");
test(function titleCaseTreatsPunctuationAsLetters() {
assertEquals(titleCase(""), "");
assertEquals(titleCase("HELLO:WORLD"), "Hello:world");
assertEquals(titleCase("HeLlO_wOrLd"), "Hello_world");
test(function titleCaseWorksWithEmoji() {
assertEquals(titleCase("👋 world"), "👋 World");
assertEquals(titleCase("🤷‍♀ing emoji"), "🤷‍♀ing Emoji"); // emoji counts as first letter of word
if (import.meta.main) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.