【问题标题】:How to find text in a string using google script?如何使用谷歌脚本在字符串中查找文本?
【发布时间】:2015-05-19 11:36:36
【问题描述】:

我尝试了 indexOf()、findText() 和其他几种在 google app 脚本中的文本中查找字符串模式的方法。以上方法均无效。

var str="task is completed";

我从谷歌电子表格中得到这个字符串。

我只是想看看上面的字符串是否包含字符串“task”。

【问题讨论】:

  • task 在这个条件下出现在字符串中 -- if(str.indexOf("task")>-1){ }
  • 我收到此错误消息:TypeError: Cannot call method "indexOf" of undefined.

标签: javascript google-apps-script google-sheets


【解决方案1】:

您需要检查str 是否存在:

if (str) {
    if (str.indexOf('task') > -1) {
        // Present
    }
}

或者,您可以使用testregex

/task/.test("task is completed");

/task/.test(str);
  1. /task/:正则表达式匹配“任务”
  2. test:针对正则表达式测试字符串并返回布尔值

【讨论】:

  • 这对于所要求的内容来说太过分了
  • 好吧,它只是添加了下面现有答案中已经存在的内容。
  • @ZigMandel I'm getting this error message : TypeError: Cannot call method "indexOf" of undefined.
【解决方案2】:

一个简单的str.indexOf("test")>=0 就可以了。有用。不知道为什么你说它不起作用,因为你没有显示任何代码来指出问题。
如果你想检查无论大小写使用str.toLowerCase().indexOf("test")

【讨论】:

  • I tried indexOf(), findText() and other few methods for finding a string pattern in a text in google app script. None of the above method works.
  • 您仍然没有显示不起作用的代码。更新您的问题并将其包含在内
猜你喜欢
  • 2011-10-11
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多