计算在具有多个表单字段的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个(。也许插入一个按钮手动允许用户运行脚本会更好?

对此,有什么更稳定、更优雅的方法呢?已经谢谢你的帮助了。

为什么不迭代问题并分别计算单词?不确定为什么要连接它。

function countAllWords() {
var wordsCount = 0;
var lastQuestionIndex = 4;
for(var i = 1; i <  lastQuestionIndex; i++) {
var answerText = this.getField("question" + str(i)).value;
wordsCount += countWords(answerText);
}
return wordsCount;
}

最新更新