H3

H3

by Alex McWhinnie

HTML

<link rel="stylesheet" href="https://assets.ipums.org/_css/jsfiddle.1.0.css">
<script src="https://assets.ipums.org/_js/load-fonts.1.3.js"></script>
<h3>
  This is an H3 heading
</h3>

JavaScript

String.prototype.toTitleCase = function(){
  var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|is|nor|of|on|or|per|the|to|vs?\.?|via)$/i;

  return this.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){
    if (index > 0 && index + match.length !== title.length &&
      match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
      (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
      title.charAt(index - 1).search(/[^\s-]/) < 0) {
      return match.toLowerCase();
    }

    if (match.substr(1).search(/[A-Z]|\../) > -1) {
      return match;
    }

    return match.charAt(0).toUpperCase() + match.substr(1);
  });
};

// get all h3 elements to convert.  this could be generalized?
var h3s = document.body.querySelectorAll("h3");

for(var i = 0; i < h3s.length; i++) {
  // if the element has a computed style of "capitalize", override it with none.
  // and then convert it to title case.
  if( window.getComputedStyle(h3s[i], null)["textTransform"] == "capitalize") {
    h3s[i].style.textTransform="none";
    
    // convert the content to title case
    h3s[i].textContent = h3s[i].textContent.toTitleCase();
  }
};