Skip to content

Instantly share code, notes, and snippets.

@ckunte
Created February 21, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckunte/4315f9d2f4e2421ebb3d92bb647f873e to your computer and use it in GitHub Desktop.
Save ckunte/4315f9d2f4e2421ebb3d92bb647f873e to your computer and use it in GitHub Desktop.
Turn CAPITALISED words into SMALL CAPS on the fly on web pages

Turn CAPITALISED words into SMALL CAPS on the fly

The in-line script searches contents of the body of the page for capitalised words with two or more characters, and when found, wraps them in abbr opening and closing html tags, which can then be made to look like small caps.

Javascript

This following script can be added to the head section of a page enclosed within opening and closing script tags.

  window.onload = scotf;
  function scotf() {
    document.body.innerHTML=document.body.innerHTML.replace(/[A-Z]{2,}/g, '<abbr>$&</abbr>');}

Styling

abbr {
  letter-spacing:0.3ch; /* adjust as appropriate */
  font-size: 81%;       /* adjust as appropriate */
}

Last updated: 2020-02-21 16:33 ckunte

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Turn Capitalised words into small-caps on the fly with Javascript</title>
<meta name="author" content="Chetan Kunte">
<!-- small caps script -->
<style type="text/css">
abbr {letter-spacing:0.3ch;font-size: 81%}
pre { padding: 1ch}
</style>
<script type="text/javascript">
window.onload = scotf;
function scotf() {
document.body.innerHTML=document.body.innerHTML.replace(/[A-Z]{2,}/g, '<abbr>$&</abbr>');}
</script>
</head>
<body>
<h1>Turn CAPITALISED words into SMALL CAPS on the fly with Javascript</h1>
<p>
The JavaScript looks for CAPITALISED words with two or more characters and wraps it invisibly within <i>&lt;abbr&gt;</i> tag (i.e., tags do not appear in View Source), which can then be styled to look like small-caps:
</p>
<pre>
abbr {
letter-spacing:0.3ch; /* adjust as appropriate */
font-size: 81%; /* adjust as appropriate */
}
</pre>
<p>
If the web font actually has small-caps character variants, then the above can simply be styled as:
</p>
<pre>
abbr {
font-variant: small-caps;
letter-spacing:0.3ch; /* optional */
}
</pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment