diff --git a/docs/content/manual/dev/manual.yml b/docs/content/manual/dev/manual.yml index 2707736b..03043abc 100644 --- a/docs/content/manual/dev/manual.yml +++ b/docs/content/manual/dev/manual.yml @@ -1798,6 +1798,17 @@ sections: input: '["fo", "foo", "barfoo", "foobar", "foob"]' output: ['["fo","","bar","foobar","foob"]'] + - title: "`trimstr(str)`" + body: | + + Outputs its input with the given string removed at both ends, if it + starts or ends with it. + + examples: + - program: '[.[]|trimstr("foo")]' + input: '["fo", "foo", "barfoo", "foobarfoo", "foob"]' + output: ['["fo","","bar","bar","b"]'] + - title: "`trim`, `ltrim`, `rtrim`" body: | diff --git a/jq.1.prebuilt b/jq.1.prebuilt index a07bb0ff..6ec5c811 100644 --- a/jq.1.prebuilt +++ b/jq.1.prebuilt @@ -1959,6 +1959,21 @@ jq \'[\.[]|rtrimstr("foo")]\' . .IP "" 0 . +.SS "trimstr(str)" +Outputs its input with the given string removed at both ends, if it starts or ends with it\. +. +.IP "" 4 +. +.nf + +jq \'[\.[]|trimstr("foo")]\' + ["fo", "foo", "barfoo", "foobarfoo", "foob"] +=> ["fo","","bar","bar","b"] +. +.fi +. +.IP "" 0 +. .SS "trim, ltrim, rtrim" \fBtrim\fR trims both leading and trailing whitespace\. . diff --git a/src/builtin.jq b/src/builtin.jq index 30ba8478..40ef0f50 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -76,6 +76,7 @@ def fromdate: fromdateiso8601; def todate: todateiso8601; def ltrimstr($left): if startswith($left) then .[$left | length:] end; def rtrimstr($right): if endswith($right) then .[:$right | -length] end; +def trimstr($val): ltrimstr($val) | rtrimstr($val); def match(re; mode): _match_impl(re; mode; false)|.[]; def match($val): ($val|type) as $vt | if $vt == "string" then match($val; null) elif $vt == "array" and ($val | length) > 1 then match($val[0]; $val[1]) diff --git a/tests/jq.test b/tests/jq.test index 6f5a71ee..6cfb13e5 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -1508,6 +1508,10 @@ split("") ["fo", "foo", "barfoo", "foobar", "foob"] ["fo","","bar","foobar","foob"] +[.[]|trimstr("foo")] +["fo", "foo", "barfoo", "foobarfoo", "foob"] +["fo","","bar","bar","b"] + [(index(","), rindex(",")), indices(",")] "a,bc,def,ghij,klmno" [1,13,[1,4,8,13]] diff --git a/tests/man.test b/tests/man.test index c840d916..d815fde6 100644 --- a/tests/man.test +++ b/tests/man.test @@ -617,6 +617,10 @@ combinations(2) ["fo", "foo", "barfoo", "foobar", "foob"] ["fo","","bar","foobar","foob"] +[.[]|trimstr("foo")] +["fo", "foo", "barfoo", "foobarfoo", "foob"] +["fo","","bar","bar","b"] + trim, ltrim, rtrim " abc " "abc"