Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It it possible to truncate text in a groq query?

Tags:

sanity

groq

I'd like to create an excerpt from a (portable) text field. Is this something that is possible?

I know I can get the text value back using pt::text(body) and I can get values such as length from that. Is there any way to cut the text after n characters or words?

like image 397
Designer023 Avatar asked Sep 20 '25 16:09

Designer023


1 Answers

I have solved this now. I feel like it's a bit of a hack, but essentially...

  1. Get the string of the body as above: pt::text(body)
  2. Split the string into an array of every character: string::split(bodyString, "")
  3. truncate it to 255 characters: [0..255]
  4. Join it back together: array::join(truncated, "")
  5. Add an ellipsis to the end: + "..."

Joined together it can either be a set of queries piped together:

*[_type == "article" && draft != true ] | order(publishedOn desc)[0..5] {
  "excerpt": (pt::text(body)),
} | {
 "excerpt": string::split(excerpt, "")[0..255]
} | {
  "excerpt": array::join(excerpt, "") + "..."
}

Or as one query:

*[_type == "article" && draft != true ] | order(publishedOn desc)[0..5] {
     "excerpt": array::join(string::split((pt::text(body)), "")[0..255], "") + "..."
}
like image 95
Designer023 Avatar answered Sep 23 '25 13:09

Designer023



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!