Geoff Ball
Support Engineer at Sanity.io
GROQ doesn't yet include a function to match the end of a string, but we can simulate it by splitting our string on our term.
// GROQ filter
*[
string::split(@[$field], $term)[-1] == ""
]
// GROQ params
{
"field": "title",
"term": "vegetables"
}
GROQ provides a startsWith
function to match the start of a string, but doesn't yet include a function to match the end of a string. (Note: There is a match
operator, but it tokenizes and doesn't let you match patterns that include non-alphanumeric values).
There is another string function, split
, that we can use to model the functionality a function like string::endsWith()
might provide. The split
function takes a string, splits it on a separator, and returns an array of strings. The documentation provides some common use cases, such as splitting on a space to return an array of words from a sentence. By splitting on the term we want to match, we can take advantage of two features of that function:
Essentially, we're splitting the string anywhere it finds the term, then returning an array of strings containing what comes before and after those terms. If the final term of the array ([-1]
) is an empty string, it means the separator must have been at the end of the string.
In its simplest form, we could add something like the following to our GROQ query (within the filter):
string::split(title, "radish")[-1] == ""
That won't tokenize like the match
operator, meaning it won't inadvertently match "I am eating a radish." with a period at the end. (Want to match radish.
with a period? Include a period in the separator, which is the second term of the function.) What it will match is "A radish is a radish", or "don't shorten traditional to tradish", or "roast beef needs horseradish". To match a complete term at the end of the string, prepend it with a space.
string::split(title, " radish")[-1] == ""
The final example here refactors your string and search term into the params of your GROQ query (as field
and term
), making it much more reusable throughout your code base. @[$field]
might look a bit unusual, but it works out to @['title']
(or, if you like to think in terms of dot notation, @.title
, where @
is the current scope).
Support Engineer at Sanity.io
Your block styles will normally look the same in the editor and the styles dropdown. For the times you don't want that, this workaround lets you configure them differently.
Go to Create different block styles for the dropdown and editorSometimes, you just need to migrate a document or two.
Go to Ad hoc document migrationSimplify your Studio experience by hiding deprecated fields when you create new documents.
Go to Hide a deprecated field in new documentsIf you want to pass a parameter to a query that might not always be defined
Go to Handle Certain Values To Be True