How to find text in a string using google script?
Asked Answered
F

3

7

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.

var str="task is completed";

I'm getting this string from google spreadsheet.

I just want to find whether the above string contains a string "task" .

Fanatic answered 19/5, 2015 at 11:36 Comment(2)
task is present in the string with this condition-- if(str.indexOf("task")>-1){ }Heddi
I'm getting this error message : TypeError: Cannot call method "indexOf" of undefined.Fanatic
P
16

You need to check if the str is present:

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

Alternatively, you can use test and regex:

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

/task/.test(str);
  1. /task/: Regex to match the 'task'
  2. test: Test the string against regex and return boolean
Pernas answered 19/5, 2015 at 11:38 Comment(3)
this is overkill for what is being askedJermainejerman
well, it just added what was already present in an existing answer below.Jermainejerman
@ZigMandel I'm getting this error message : TypeError: Cannot call method "indexOf" of undefined.Pernas
J
4

a simple str.indexOf("test")>=0 does it. it works. not sure why you say it doesnt work as you havent shown any code to point out the problem.
if you want to check regardless of case use str.toLowerCase().indexOf("test")

Jermainejerman answered 19/5, 2015 at 12:27 Comment(2)
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.Pernas
you are still not showing the code that doesnt work. update your question and include itJermainejerman
G
0

What you need to do is make the array value a string so apps script doesn't think it's searching an array. Add double quote to your toString() function.

var arr = ["blah", "blahYES", "NOblahYES"]

for (i = 0; i < arr.length; i++){
    if(arr[i].toString().indexOf("YES") > -1) { 
        // do something awesome. 
    }
}
Grandiloquent answered 20/4, 2023 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.