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 ?
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:
=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.)