string Google Apps 脚本 - 使用 .replace 方法删除空格对我不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16547060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:55:44  来源:igfitidea点击:

Google Apps Script - remove spaces using .replace method does not work for me

stringgoogle-apps-script

提问by Calvin Ong

I am using Google Apps Script to create apps. I encounter issue when I try to remove whitespaces from my spreadsheet value. I have referred alot of posts & comments in stackoverflow and other forum too. They are all talking about using .replacemethod. However, .replacemethod does not work for me.

我正在使用 Google Apps 脚本来创建应用程序。当我尝试从电子表格值中删除空格时遇到问题。我也在 stackoverflow 和其他论坛中提到了很多帖子和评论。他们都在谈论使用.replace方法。但是,.replace方法对我不起作用。

var ItemArray = <<getValue from google spreadsheet>>
var tValue = ItemArray[0][2].toString();

for (var row = 0; row<ItemArray.length; row++)
{
   var TrimmedStrA = ItemArray[row][2].toString().replace(' ', '');
   var TrimmedStrB = tValue.replace(' ', '');

   if (TrimmedStrA == TrimmedStrB)
   {
      <<other code>>

   } //end if
} //end of loop

回答by rGil

A simple RegExp object should be used in the replace() method. \s is a simple solution to find whitespace. The 'g' provides a global match for instances of whitespace.

在 replace() 方法中应该使用一个简单的 RegExp 对象。\s 是查找空格的简单解决方案。'g' 为空白实例提供全局匹配。

t.Value.replace(/\s/g, "") 

This will get you pretty close without knowing what your data looks like.

这将使您在不知道您的数据是什么样子的情况下非常接近。

.replace() documentation here.

.replace() 文档在这里。