hugo/docs/content/en/functions/strings/Trim.md
2023-12-04 15:24:01 +01:00

1.4 KiB

title description categories keywords action aliases
strings.Trim Returns the given string, removing leading and trailing characters specified in the cutset.
aliases related returnType signatures
trim
functions/strings/Chomp
functions/strings/TrimLeft
functions/strings/TrimPrefix
functions/strings/TrimRight
functions/strings/TrimSuffix
string
strings.Trim INPUT CUTSET
/functions/trim
{{ trim "++foo--" "+-" }} → foo

To remove leading and trailing newline characters and carriage returns:

{{ trim "\nfoo\n" "\n\r" }} → foo
{{ trim "\n\nfoo\n\n" "\n\r" }} → foo

{{ trim "\r\nfoo\r\n" "\n\r" }} → foo
{{ trim "\r\n\r\nfoo\r\n\r\n" "\n\r" }} → foo

The strings.Trim function is commonly used in shortcodes to remove leading and trailing newlines characters and carriage returns from the content within the opening and closing shortcode tags.

For example, with this markdown:

{{</* my-shortcode */>}}
Able was I ere I saw Elba.
{{</* /my-shortcode */>}}

The value of .Inner in the shortcode template is:

\nAble was I ere I saw Elba.\n

If authored on a Windows system the value of .Inner might, depending on the editor configuration, be:

\r\nAble was I ere I saw Elba.\r\n

This construct is common in shortcode templates:

{{ trim .Inner "\n\r" }}