javascript - 我如何计算这些单词,使用谷歌表格中的脚本?
问题描述
我想计算一个字符串中一个单词的出现次数,但 Google 表格给了我一个错误,它无法处理表达式:
finalScores.push(preOutputTxt.match(nameArr[x])).length);
因为某处有空。我怎样才能解决这个问题?完整代码:
/**
*
*
*
* @customFunction
*/
function scoreCounting(scores, names){
//---variables---//
var scoresArr = [];
var preOutputTxt = "";
var finalScores = [];
var nameArr = [];
//---------------//
//---creating an array from names and scores (scores are in string type)---//
for(var w = 0; w < scores.length; w ++){
scoresArr.push(scores[w]);
}
for(var z = 0; z < names.length; z++){
nameArr.push(names[z]);
}
//---------------------------------------//
//---make one big string with names---//
for(var y = 0; y < scoresArr.length; y++){
preOutputTxt += scoresArr[y];
}
//----------------------------------------------//
//---counting how many times score (a name) occur, basing on name given by nameArr[]---//
for(var x = 0; x < nameArr.length; x++){
finalScores.push(preOutputTxt.match(nameArr[x])).length);
}
return finalScores;
}
解决方案
正如 Tedinoz 所提到的,如果您可以共享电子表格,那么提供特定帮助会更容易。
但与此同时,这里有两个片段有助于解释如何在较长的字符串中获取单词的计数。
示例 1:如果您使用match()
name 作为输入,您将只获得第一个匹配项。
[这是因为该方法需要一个正则表达式。并且传递一个字符串(或一个设置为字符串的变量)类似于没有修饰符的正则表达式。]
function example1() {
var preOutputTxt = 'abcabcabc';
var name = 'abc';
var output = preOutputTxt.match(name);
Logger.log('Output is %s. Length is %s.', output, output.length);
}
// Output is [abc]. Length is 1.0.
示例 2:但是如果您使用带有全局修饰符的正则表达式,您将获得所有匹配项。
function example2() {
var preOutputTxt = 'abcabcabc';
var name = 'abc';
var re = new RegExp(name, 'g');
Logger.log('Regular expression is %s', re);
var output = preOutputTxt.match(re);
Logger.log('Output is %s. Length is %s.', output, output.length);
}
// Regular expression is /abc/g
// Output is [abc, abc, abc]. Length is 3.0.
推荐阅读
- python - 计算排序方法的平均时间
- python - 我如何将 CNN 层放入我的循环神经网络
- angular - 更好地组织 NGXS 状态
- c - 如何在 C 中为输入和输出文件运行命令行参数
- python - Kivy 应用程序:在手机上使用 __init__ 但在计算机项目中有效
- mysql - 在单节点数据库上连接两个一对一表的性能是否与在等效的非规范化表上进行纯选择相同?
- php - 我正在尝试更改 EXCEL 中列的类型,但不知道出了什么问题?
- java - HTML 返回用“-”替换文本值
- ruby-on-rails - 如何让迁移错误告诉我更多信息?
- r - 从复选框中动态选择时渲染传单的问题