Word Count/Character Count in Editor Using Scripting (JS)

Hi @Sebastian,

Is there a simple way to use JS in scripting of a readTime value for a Schema field of type string where characters can be counted for vanilla/custom editor and then saved as a number field in Squidex. On every update of the content the formula reruns on the character/word count there by allowing a simple read time kind of functionality at Squidex Level.

Hi @Sebastian , Could you please help on this query?

Editor:

We have a custom editor included in squidex like,

The editor has word count at the footer section of editor.

Requirement:

Now our requirement is we need to update the word count from the custom editor to the input field which we have placed next to it which has been named as wordCount?

As per the example the word count of 2 needs to be updated in the input field wordCount .

Could you please help us to achieve the expected result through any JS scripts?

I do not see a direct fix, but you could use a json field with a custom editor.

Instead of just saving the string you save your content as a json object.

{
  "text": "<p>Hello World</p>",
  "wordCount": 2
}

The only disadvantage is that json fields cannot be searched.

You could also use the approach to add two more fields:

  • textAndWordCount (JSON)
  • text (String)
  • wordCount (Number)

then you a normal schema to extract both fields from the json field

ctx.data.text.iv = ctx.data.textAndWordCount.iv.text
ctx.data.wordCount.iv = ctx.data.wordCount.iv.text
replace()

another alternative is a script, but this is complicated.

First you have to get the texts from the html, this is complicated and you have to search for a regex solution or so.

Then word count should be easy as long as you do not have to deal with chinese characters or so.

I have added a few helpers to the scripting:

  • html2Text: Converts html to plain text
  • markdown2Text: Converts markdown to plain text
  • characterCount: Counts the number of characters in a text.
  • wordCount: Counts the number of words in a text.

In your case you could do something like

ctx.data.wordCount.iv = wordCount(html2Text(ctx.data.text.iv));
replace();

ATTENTION: It is not deployed yet.

Hi @Sebastian , We have included this last approach which you have mentioned latest.

And in the article when I type the words in editor and click save, I am getting the following error,

Whether the deployment not yet happen for the latest helpers which you have mentioned?

I have added a big ATTENTION to my latest post.

@Sebastian Is this deployed can we use it to auto calculate the words count and save it as a variable in Squidex

I think so, just try it out please.