Search code examples
tinymce

Why there is a difference of 1 word in word count shown in TinyMCE editor and Function that returns text statistics for an editor instance by id


I was trying to limit the word count in TinyMCE editor. For that used a function suggested in the documentation of TinyMCE https://www.tiny.cloud/docs-3x/howto/words/. This function always returns word count greater by 1 than the word count shown in the editor's status bar. For eg: if we empty the editor, the word count in status bar of editor shows 0 but function returns 1. Likewise the word count is 10 on editor, function returns 11. Why that function returns different value and how can I match these values?


Solution

  • The link you provide is to TinyMCE 3 documentation which is out of date. TinyMCE 5 is the currently released editor and TinyMCE 6 will be released shortly.

    In TinyMCE 4+ you should use the API for the wordcount plugin which is documented here:
    https://www.tiny.cloud/docs/plugins/opensource/wordcount/#api

    If you use the wordcount API it will match what is displayed in the editor.

    var wordcount = tinymce.activeEditor.plugins.wordcount;
    
    console.log(wordcount.body.getWordCount());
    console.log(wordcount.body.getCharacterCount());
    console.log(wordcount.body.getCharacterCountWithoutSpaces());
    
    console.log(wordcount.selection.getWordCount());
    console.log(wordcount.selection.getCharacterCount());
    console.log(wordcount.selection.getCharacterCountWithoutSpaces());