Google Sheets Script Wildcards

6k Views Asked by At

I know i can use wildcards with formulas like ;

=COUNTIF(A:A ; "*text*")

I want to run my code if A1 contains "text".

A1 = "test text"

Can anyone help me ?

3

There are 3 best solutions below

0
On BEST ANSWER

My solution :

 if(test.indexOf("2,")>-1)
{
    my code goes here
    }
1
On
=IF(COUNTIF(A1, "*text*"), "your code here", "Code not run: A1 doesn't contain 'text'")

Is this what you had in mind – formula code? Or do you want to use Google Apps Script?

(There may be a more intuitively named function than COUNTIF() for this, but it does the trick.)

1
On

For Google Apps Script you can use regular expressions. Any statement surrounded by forward slashes is interpreted as a regex if you hardcode it in apps script:

/.*text.*/

Note that wildcards are used slightly differently in RegExps: You need to include a dot . before your asterisk *:
    COUNTIF():      *text*
    regex:                  /.*text.*/

So a quick script would look like this:

function matchText(text){
    try {
        var pattern = /.*text.*/;
        var isMatch = text.match(pattern)[0];
        return isMatch
    } catch (e) {
    return e.toString();
  }
};

A generalized custom function:

function matchText(text,pattern){
    try {
        var isMatch = text.match(pattern)[0];
        return isMatch
    } catch (e) {
    return e.toString();
  }
};

You can also still do this with native formulas using regexextract or regexmatch, which is always my favorite. Remember to use the correct regex wildcards notation with these: dot before the asterisk: .*. Or just use text by itself, which automatically would find any instance of it:

enter image description here