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!
({
  name: 'SplitString',
  body: (
    (
      ['string', 'delimiter'],
      (
        ((("string"))),
        ("SplitString only accepts strings"),
        (
          (
            ("string"),
            (["[^\\", ("delimiter"), "]+"])
          ),
          ("res", (["data"], ("res")))
        )
      )
    )
  )
})
{
  ref: ("SplitString"),
  ts: 1653676193440000,
  name: 'SplitString',
  body: ((["string", "delimiter"], (((("string"))), ("SplitString only accepts strings"), ((("string"), (["[^\\", ("delimiter"), "]+"])), ("res", (["data"], ("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!
("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

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!