8

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" .

2
  • 2
    task is present in the string with this condition-- if(str.indexOf("task")>-1){ } Commented May 19, 2015 at 11:37
  • I'm getting this error message : TypeError: Cannot call method "indexOf" of undefined. Commented May 19, 2015 at 11:39

3 Answers 3

17

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
Sign up to request clarification or add additional context in comments.

3 Comments

this is overkill for what is being asked
well, it just added what was already present in an existing answer below.
@ZigMandel I'm getting this error message : TypeError: Cannot call method "indexOf" of undefined.
5

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")

2 Comments

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.
you are still not showing the code that doesnt work. update your question and include it
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. 
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.