Skip to content

Instantly share code, notes, and snippets.

@joshlawton
Last active April 5, 2020 07:41
Show Gist options
  • Save joshlawton/0be31fe0cfc11683116b769a56831c71 to your computer and use it in GitHub Desktop.
Save joshlawton/0be31fe0cfc11683116b769a56831c71 to your computer and use it in GitHub Desktop.
Regex to match a set of words--but only if they don't appear at the beginning of the string or line
/**
* When formatting a string in title case, we capitalize the all words except articles, conjunctions,
* copulae (forms of "to be"), and prepositions (with four or fewer characters).
* The first and last words are always capitalized.
*
* Source: https://en.wikipedia.org/wiki/Letter_case#Title_case
*
* This regex uses a negative lookahead to only match the keywords if they aren't at the beginning of a line.
* Note that this regex uses the multiline flag, indicating to match each line, not just the entire string.
*
* Additional resources:
* - https://titlecaseconverter.com
* - https://saijogeorge.com/title-case-converter/
*/
/(?<!^)(\b(A|Am|Amid|An|And|Are|As|At|Atop|Be|Been|But|By|Down|For|From|In|Into|Is|Like|Mid|Near|Next|Nor|Of|Off|On|Onto|Or|Out|Over|Past|Per|Plus|Pro|Sans|Save|So|Than|The|Till|To|Unto|Up|Upon|Via|Vice|Vs|Was|Were|With|Yet)\b)+/gm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment