if string.match() doesn't match, why is execution of google apps script cancelled?

孤人 提交于 2020-03-23 12:03:05

问题


if I use the following function within Google Sheets it doesn't return the value "not found". The logs tell me: "Execution cancelled".

This happens at the line:

var found = text.match(re);

If I change searchText to "abc" it works like a charme.

function example()
{
  var text = "abc cba";
  var searchText = "abcd";

  var re = new RegExp(searchText,"g");

  var found = text.match(re);

  if (found === undefined) { 
    return "not found";
  }
  else {
    return found;
  }
} 

Why is the script execution cancelled and how can I prevent this behavior without using the regex twice by using e.g. text.search(re) combined with if before the match() ?


回答1:


Cause:

The return value of string.match ,

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

and

null !== undefined

So, when it's null, the else statement executes and returns null to sheet. The "execution cancelled" is irrelevant and probably from old logsissue

Solution:

Use null to compare return value.

Snippet:

if (found === null) { 


来源:https://stackoverflow.com/questions/60543633/if-string-match-doesnt-match-why-is-execution-of-google-apps-script-cancelle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!