First Sentence jQuery Plugin

Alright, so I freely admit that this is one of the more “niche” plugins I have ever written. A colleague of mine was working on a WordPress blog for one of the company properties, and the designer wanted to have the first sentence of a paragraph in the ‘Recent Articles’ section highlighted in a different colour.

Now, this would be all fine and dandy, because you could just set the colour of the first sentence of the post that colour, and all would be great. Except then the first sentence would ALWAYS be that colour, everywhere. In the post, in the excerpt, everywhere. The colleague had tried using the ::first-line pseudo-selector from CSS, but depending on the screen size (Responsive design FTW) and the sentence, this might mean that more than the first sentence, or significantly less than the first sentence, would be highlighted.

A better solution was needed. Armed with a full stomach from lunch, I set out to get something that would work for them. I looked at a few different solutions, before just giving up and realizing that I was going to have to use regexp. Which led to my remembering a great quote.

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

So despite my better judgement, I delivered a solution that uses regexp to grab the first “sentence” of text in an HTML element. It doesn’t strip out tags, so if you have tags in the first sentence of your HTML, it will break. But this wasn’t a use case, so I didn’t account for it. If someone was interested in taking this further, I would welcome the contribution. The logic is that all text up to the first sentence-ending punctuation (?, ., or !) is then wrapped in a tag.

I also hardcoded a class name into the plugin. It’s horrible, I know. But if you set the class ‘.firstSentence’ in your CSS to be the styling you want to use on the first sentence (naming schemes rock), it will work. If you don’t like that class, edit the plugin. Again, I would welcome the contribution. Theoretically, you could pass the class name as an argument into the plugin, which would have a default set and accept the parameter.

Demo here. Uncompressed code here. Minified code (232b!) here.

Published 7 Mar 2014

Writing better code by building better JavaScript
Don Burks on Twitter