问题
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