Arun Prakash
Arun Prakash

Reputation: 441

How to find text in a string using google script?

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

Upvotes: 8

Views: 64953

Answers (3)

Lucas Reilly
Lucas Reilly

Reputation: 1

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

Upvotes: 0

Tushar
Tushar

Reputation: 87203

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

Upvotes: 17

Zig Mandel
Zig Mandel

Reputation: 19835

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

Upvotes: 5

Related Questions