Skip to content
Latchkey

jq split, join, ltrimstr : Cut and Trim Strings

jq split(sep) cuts a string into an array on a separator, join(sep) concatenates one back into a string, and ltrimstr/rtrimstr remove a literal prefix or suffix.

Refs like refs/heads/main and comma lists from API fields are easiest to handle by splitting, trimming, and rejoining in CI.

What it does

split(sep) divides a string into an array of pieces around the separator. join(sep) is the inverse, concatenating array elements with the separator (elements must be strings, or null treated as empty). ltrimstr(prefix) removes the prefix if the string begins with it, otherwise returns it unchanged, and rtrimstr(suffix) does the same at the end; both are literal, not regex, and pass non-strings through unchanged.

Common usage

Terminal
# strip the ref prefix to get the branch
jq -r '.ref | ltrimstr("refs/heads/")' event.json
# take the branch name from a full ref by splitting
jq -r '.ref | split("/") | last' event.json
# drop a v on a tag, remove a .json suffix
echo '"v1.2.3"' | jq -r 'ltrimstr("v")'
echo '"config.json"' | jq -r 'rtrimstr(".json")'
# parse a comma list, trim, rejoin
jq -r '.labels | split(",") | map(ltrimstr(" ")) | join(",")' issue.json

Functions

FunctionWhat it does
split(s)String to array on separator s
split("re"; "g")Regex split (two-argument form)
join(s)Array to string with separator s
ltrimstr(s) / rtrimstr(s)Remove a literal prefix/suffix if present
last / .[-1]Take the final piece

In CI

ltrimstr is a no-op when the prefix is absent, so it is safe on a mixed list of refs without first checking startswith; that makes it ideal for normalizing values that may or may not carry a prefix.

Common errors in CI

"jq: error: split input and separator must be strings" means the input was not a string; coerce with tostring or check the field exists. "jq: error: Cannot iterate over null" from join means the value was null, not an array. ltrimstr never errors on a missing prefix; it silently returns the string unchanged, which can mask a wrong prefix.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →