string <- ' some text on line one;
and then some text on line two '
"Trimming" whitespace typically refers to removing both leading and trailing whitespace from a string. This may be done using a combination of the previous examples. gsub
is used to force the replacement over both the leading and trailing matches.
Prior to R 3.2.0
gsub(pattern = "(^ +| +$)",
replacement = "",
x = string)
[1] "some text on line one; \nand then some text on line two"
R 3.2.0 and higher
trimws(x = string)
[1] "some text on line one; \nand then some text on line two"
Prior to R 3.2.0
sub(pattern = "^ +",
replacement = "",
x = string)
[1] "some text on line one; \nand then some text on line two "
R 3.2.0 and higher
trimws(x = string,
which = "left")
[1] "some text on line one; \nand then some text on line two "
Prior to R 3.2.0
sub(pattern = " +$",
replacement = "",
x = string)
[1] " some text on line one; \nand then some text on line two"
R 3.2.0 and higher
trimws(x = string,
which = "right")
[1] " some text on line one; \nand then some text on line two"
gsub(pattern = "\\s",
replacement = "",
x = string)
[1] "sometextonlineone;andthensometextonlinetwo"
Note that this will also remove white space characterse such as tabs (\t
), newlines (\r
and \n
), and spaces.