Twitter summary cards for your website

In this tutorial I outline what steps I took to implement Twitter summary cards onto my website.

<meta name="twitter:card" content="summary">
<meta name="twitter:title" content={{title || "Kequc"}}>
<meta name="twitter:description" content={{description || "Javascript, web technology, skunks."}}>
<meta name="twitter:site" content="@mr_kequc">
<meta name="twitter:image" content="http://www.kequc.com/images/skunk-badge.png">

These are the necessary meta attributes you need to add to the head of your pages. Where all except twitter:image are required.

Technically twitter:site doesn't need to be there either but there isn't any reason not to have it and benefit from some extra Twitter goodies. Include your Twitter handle (including @ sign).

Once you have published the page to the web you'll need to visit their Validator service and plug in the url. It will display a preview of your card and Twitter will do some magic behind the scenes to begin capturing this data off of your pages.

The description field is a maximum of 200 characters. I decided I would summarise my articles using the first paragraph. The following code resides in my article update action.

function blurb (text)
{
    if (!text)
        return;

    let sentences = text.trim().split(/\r\n|\r|\n/)[0].split(".");
    if (!sentences.length)
        return;

    let chars = 0;
    for (let i = 0; i < sentences.length; i++) {
        chars += sentences[i].length + 1;
        if (chars >= 200) {
            if (i <= 0)
                return;
            return sentences.slice(0, i).join(".") + ".";
        }
    }

    return sentences.join(".");
}

First split the content of the first paragraph into sentences. Then start counting characters, once we have reached the limit, return all sentences which fit up until that point. Be sure to re-include that trailing period otherwise things look weird.

If the whole paragraph fits then we safely return all of it.