计算具有多个表单字段的pdf中键入单词的总数 javascript

问题描述

我的第一个JavaScript问题在这里,所以这可能是非常基本的。 我目前正在准备一个带有多个表单输入字段的pdf表单,允许用户在Adobe Acrobat PRO DC中输入。

要求用户回答一些随笔风格的问题,并将其文本回复填写到每个字段中。根据问题的不同,答案的长度可能在几个词到数百个词之间。

我现在只想在计算选项卡(自定义计算脚本)中添加一个使用javascript的附加字段,该字段会计算所有先前字段中输入的单词数,并向用户显示用户已经写过。

我的第一个原始方法是首先创建一个附加(不可见)字段,该字段将不同字段的所有答案简单地连接为一个大答案,然后计算该字段的单词数。

下面是一些示例代码

 //first step combine all answers

this.getField("allAnswers").value = this.getField("question1").value + " " +
                                    this.getField("question2").value + " " +
                                    this.getField("question3").value + " " +
                                    this.getField("question4").value;         
//code would proceed until the last question


//A function to count the words which is defined as a general Document script
//("https://www.tutorialspoint.com/how-to-count-a-number-of-words-in-given-string-in-javascript")
  
function countWords(str) {
     str = str.replace(/(^\s*)|(\s*$)/gi,"");
     str = str.replace(/[ ]{2,}/gi," ");
     str = str.replace(/\n /,"\n");
     return str.split(' ').length;
  }

//using that function on the allAnswers field
this.getField("totalNumberOfWords").value= countWords(this.getField("allAnswers").value);

尽管这种方法将不同的答案复制到“ allAnswers”字段中,然后对单词进行计数,但我发现来自不同字段的字符串被多次包含,因此非常迅速地增加了单词计数。为什么会这样? 我也有点担心,此过程可能会导致pdf本身运行得更慢,尤其是如果在每次用户键入某些内容的同时同时评估了许多表单字段(超过50个)时,尤其如此。也许改为插入一个按钮手动允许用户运行脚本会更好?

对此有什么更稳定,更优雅的方法? 已经感谢您的帮助。

解决方法

为什么不遍历问题并分别计算单词数?不知道为什么要串联它。

public function tasks()
{
   return $this->hasManyThrough(
     Task::class,Project::class,'user_id',// Foreign key on projects table...
     'project_id',// Foreign key on tasks table...
     'id',// Local key on users table...
     'id' // Local key on projects table...
   );
}