Created
August 29, 2021 02:34
-
-
Save ryon/0868cb8ae754981fe4c1f03425f4f4ec to your computer and use it in GitHub Desktop.
John Gruber Title Case Bookmarklet Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// enter this code on e.g., https://bookmarklets.org/maker/ to create a bookmarklet | |
const input = prompt('Enter text to convert to Title Case'); | |
prompt('Converted text below:', input.toTitleCase()); | |
/* To Title Case © 2018 David Gouch | https://github.com/gouch/to-title-case */ | |
// eslint-disable-next-line no-extend-native | |
String.prototype.toTitleCase = function () { | |
'use strict' | |
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|v.?|vs.?|via)$/i | |
var alphanumericPattern = /([A-Za-z0-9\u00C0-\u00FF])/ | |
var wordSeparators = /([ :–—-])/ | |
return this.split(wordSeparators) | |
.map(function (current, index, array) { | |
if ( | |
/* Check for small words */ | |
current.search(smallWords) > -1 && | |
/* Skip first and last word */ | |
index !== 0 && | |
index !== array.length - 1 && | |
/* Ignore title end and subtitle start */ | |
array[index - 3] !== ':' && | |
array[index + 1] !== ':' && | |
/* Ignore small words that start a hyphenated phrase */ | |
(array[index + 1] !== '-' || | |
(array[index - 1] === '-' && array[index + 1] === '-')) | |
) { | |
return current.toLowerCase() | |
} | |
/* Ignore intentional capitalization */ | |
if (current.substr(1).search(/[A-Z]|\../) > -1) { | |
return current | |
} | |
/* Ignore URLs */ | |
if (array[index + 1] === ':' && array[index + 2] !== '') { | |
return current | |
} | |
/* Capitalize the first letter */ | |
return current.replace(alphanumericPattern, function (match) { | |
return match.toUpperCase() | |
}) | |
}) | |
.join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment