The Fauna service will be ending on May 30, 2025.

For more information on the service wind down, see our announcement and the Fauna Service End-of-Life FAQ.

Split a string by a delimiter

Problem

You want to split a string on a specified delimiter and return an array of results.

Solution

You can use the Map, FindStrRegex, and Concat functions to achieve the desired result. The following example creates a user-defined function which splits an input string on a specified delimiter and returns the results as elements of an array.

Copied!
CreateFunction({
  name: 'SplitString',
  body: Query(
    Lambda(
      ['string', 'delimiter'],
      If(
        Not(IsString(Var("string"))),
        Abort("SplitString only accepts strings"),
        Map(
          FindStrRegex(
            Var("string"),
            Concat(["[^\\", Var("delimiter"), "]+"])
          ),
          Lambda("res", Select(["data"], Var("res")))
        )
      )
    )
  )
})
{
  ref: Function("SplitString"),
  ts: 1653676193440000,
  name: 'SplitString',
  body: Query(Lambda(["string", "delimiter"], If(Not(IsString(Var("string"))), Abort("SplitString only accepts strings"), Map(FindStrRegex(Var("string"), Concat(["[^\\", Var("delimiter"), "]+"])), Lambda("res", Select(["data"], Var("res")))))))
}
Query metrics:
  •    bytesIn:  391

  •   bytesOut:  491

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:   24

  • writeBytes:  582

  •  queryTime: 29ms

  •    retries:    0

Once your SplitString UDF is created, you can use it to split strings on a specified delimiter.

Copied!
Call("SplitString", "red|blue|pink", "|")
[ 'red', 'blue', 'pink' ]
Query metrics:
  •    bytesIn:  56

  •   bytesOut:  34

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 9ms

  •    retries:   0

\