diff --git a/NAMESPACE b/NAMESPACE index 026354fb..da5870fd 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -31,6 +31,7 @@ export(str_replace_na) export(str_sort) export(str_split) export(str_split_fixed) +export(str_squish) export(str_sub) export(str_subset) export(str_to_lower) diff --git a/R/pad-trim.r b/R/pad-trim.r index b02d240a..d899e839 100644 --- a/R/pad-trim.r +++ b/R/pad-trim.r @@ -89,3 +89,17 @@ str_trim <- function(string, side = c("both", "left", "right")) { both = stri_trim_both(string) ) } + +#' Trim whitespace from start, middle, and end of string. +#' +#' @param string A character vector. +#' @return A character vector. +#' @export +#' @seealso \code{\link{str_trim}} to see end-only trimming +#' @examples +#' str_squish(" String with trailing, middle, and leading white space\t") +#' str_squish("\n\nString with excess, trailing and leading white space\n\n") +str_squish <- function(string) { + stri_trim_both(str_replace_all(string,"\\s+"," ")) +} + diff --git a/man/str_squish.Rd b/man/str_squish.Rd new file mode 100644 index 00000000..76b86028 --- /dev/null +++ b/man/str_squish.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pad-trim.r +\name{str_squish} +\alias{str_squish} +\title{Trim whitespace from start, middle, and end of string.} +\usage{ +str_squish(string) +} +\arguments{ +\item{string}{A character vector.} +} +\value{ +A character vector. +} +\description{ +Trim whitespace from start, middle, and end of string. +} +\examples{ +str_squish(" String with trailing, middle, and leading white space\\t") +str_squish("\\n\\nString with excess, trailing and leading white space\\n\\n") +} +\seealso{ +\code{\link{str_trim}} to see end-only trimming +} diff --git a/tests/testthat/test-trim.r b/tests/testthat/test-trim.r index 3a50d47e..3e491345 100644 --- a/tests/testthat/test-trim.r +++ b/tests/testthat/test-trim.r @@ -16,3 +16,9 @@ test_that("side argument restricts trimming", { expect_equal(str_trim(" abc ", "left"), "abc ") expect_equal(str_trim(" abc ", "right"), " abc") }) + +test_that("squishing all removes all excess spaces and tabs", { + expect_equal(str_squish("ab\t\tc\t"), "ab c") + expect_equal(str_squish("\ta bc"), "a bc") + expect_equal(str_squish("\ta\t bc\t"), "a bc") +})