DescTools (version 0.99.13)

StrTrim: Remove Leading/Trailing Whitespace From A String

Description

The function removes all spaces, tabs and newlines from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved. Trim with method "left" deletes only leading whitespaces, "right" only trailing. Designed for users who were socialized by SQL...

Usage

StrTrim(x, pattern = " \t\n", method = "both")

Arguments

x
the string to be trimmed.
pattern
the pattern of the whitespaces to be deleted, defaults to space, tab and newline: " \t\n".
method
one out of "both", "left", "right". Determines on which side the string should be trimmed. Default is "both".

Value

  • the string x without whitespaces

Details

The functions are defined depending on method as both: gsub( pattern=gettextf("^[%s]+|[%s]+$", pattern, pattern), replacement="", x=x) left: gsub( pattern=gettextf("^[%s]+",pattern), replacement="", x=x) right: gsub( pattern=gettextf("[%s]+$",pattern), replacement="", x=x)

See Also

String functions: trimws, nchar, match, grep, regexpr, substr, sub, gsub, StrTrunc, StrDist

Examples

Run this code
StrTrim("Hello world! ")

StrTrim("Hello world! ", method="left")
StrTrim("Hello world! ", method="right")

# user defined pattern
StrTrim("..Hello ... world! ", pattern="\\.")

Run the code above in your browser using DataCamp Workspace