Tech Note: A Bookmarklet to Count Selected Characters and Words on a Web Page
Here, have a bookmarklet that counts characters and words in selected text on a web page:
javascript:(function(){var a=(document.selection?document.selection.createRange().text:document.getSelection()).toString();alert(a.length?"Characters: "+a.length+"\nWords: "+a.replace(/\s{2,}/g," ").split(" ").length:"No text selected.")})();
I bashed this out today because I wanted to easily be able to see how many words were in a given article; I used to copy and paste the article into a new BBEdit window and see the count there, but this is much simpler - just select the text and click the bookmarklet.
You can just select this code, then drag it to your browser’s bookmarks bar and give it a title. Or you can drag this nice button to the bookmarks bar instead and the title will already be filled in:
Here’s the code in a more readable form with indentation, before being minified.
It’s very simple, actually; just gets the selected text (in a way that’s compatible with IE or everything else), then puts up an alert box showing the count. The only tricky part is the regular expression in line 10 — it replaces all runs of more than one whitespace character with just one space, so when it splits the text by spaces it doesn’t end up with blank words in the array.
(You can’t drag the following code to the bookmarks bar - use the button above for that.)
(function() {
var selected = (
document.selection
? document.selection.createRange().text
: document.getSelection()
).toString();
alert(
selected.length
? 'Characters: ' + selected.length + '\nWords: ' + selected.replace(/\s{2,}/g,' ').split(' ').length
: 'No text selected.'
);
}());
It could be refined some more — right now it won’t count selected text that’s inside a frame or iframe, just in the main body of a page.