删除 google 应用程序脚本中字符串中的尾随空格

Remove trailing spaces in string in google apps script

我按“Id”分组并在 google 应用程序脚本中获取“Total_Weight”的总和。这是计算的结果。

res_1 output:

[ { Id: '400 ', Total_Weight: 484308 },
  { Id: '500W', Total_Weight: 13232 } ]

在此之后,我有一个 if-else 子句,它循环遍历上面数组中的“Id”并进行一些计算。

res_1.forEach((r2,i2)=>{
  if (r2['Id']=="400") {
    var cost = (r2['Total_Weight']/1000)*cost
    NewArray.push([r2['Id'], cost]);
  }
  else if (r2['Id']=="400W") {
    var cost = (r2['Total_Weight']/1000)*cost
    NewArray.push([r2['Id'], cost ]);
  }
}

我的挑战是在“res_1”中,第一个 ID 是“400”(400 后跟 space)。因此,当谈到 for 循环时,它不会进入第一个 if 子句。我尝试替换 spaces,但效果不佳。

有什么办法可以解决这个问题吗?任何线索都会很棒。

尝试在 res_1 输出上使用 .replace 调用,如下所示:

var res_1_trim = res_1.replace(/\s/g, "")

res_1_trim.forEach((r2,i2)=>{
  if (r2['Id']=="400") {
    var cost = (r2['Total_Weight']/1000)*cost
    NewArray.push([r2['Id'], cost]);
  }
  else if (r2['Id']=="400W") {
    var cost = (r2['Total_Weight']/1000)*cost
    NewArray.push([r2['Id'], cost ]);
  }
}

\s 是一种查找空白的解决方案,“g”提供了对空白实例的匹配。(.replace documentation)