Count number of instances of a specific character in a draft

I prepare Instagram posts’ captions in Drafts using a rather long TextExpander snippet. As a result, it’s easy for me to end up with more #hashtags than Instagram will allow on a post. I’m wondering if there’s a way to count up the number of instances of “#” in a draft? Bonus points if it can save me some mental arithmetic and subtract 27 (the current magic number, if memory serves) from the total, thereby letting me know how many I need to trim.

A one-step action with this JavaScript should do it.

var d = draft.content;
var tagsOnly = d.replace(/[^#]/g, '');
var tagsLeft = 27 - tagsOnly.length;
alert(tagsLeft + " hashtags left");
1 Like

According to this article, the current limit is 30 hash tags, so I’ve initialised my version at this below.

I’ve taken it a bit further than just indicating you how many hash tags you have and how many you have left; as per your original request. This draft action will also tell you how many hash tags over you are if you have used too many, or even that you have exactly reached the limit.

Like the solution from @drdrang above, this is actually a single script step in an action. It’s quite a few more lines, but this is mostly just building up different messages for each of the three possible variations.

//Number of allowed hash tags
const limitHash = 30;

//Count hash tag marker occurrences
let countHash = (draft.content.match(/#/g) || []).length;

//Build a response message and display it
let strMsg = "You are using " + countHash + " hash tags in your post.\n\n";
if(countHash > limitHash)
{
    strMsg += "WARNING: You are using " + (countHash - limitHash) + pluralise(countHash - limitHash, " hash tag") + " over the limit of " + limitHash + ".";
}
else
{
    if(limitHash > countHash)
    {
       strMsg += "You can use another " + (limitHash - countHash) + pluralise (limitHash - countHash, " hash tag") + " before you hit the limit of " + limitHash + ".";
    }
    else
    {
        strMsg += "Don't add any more hash tags. You are on the limit of " + limitHash + pluralise(limitHash, " hash tag") + "."
    }
}
alert(strMsg);

//Add an s if not singular
function pluralise(p_intVal, p_strText)
{
    if (p_intVal == 1)
    {
        return p_strText;
    }
    else
    {
        return p_strText + "s";
    }
}
1 Like

I love that @sylumer’s regex approach was to straightforwardly count the hashes, whereas mine was to find and delete everything that wasn’t a hash.

2 Likes

Thanks, Doctor! :sunglasses::+1: That looks perfect.

Many thanks — this is so great!