diff --git a/NAMESPACE b/NAMESPACE index 7d63581d..3bc2c491 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -33,6 +33,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/NEWS.md b/NEWS.md index 547e4d5f..72b567f7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,6 +12,8 @@ * `str_remove()` and `str_remove_all()` functions. These wrap `str_replace()` and `str_replace_all()` to remove patterns from strings. (@Shians, #178) + +* `str_squish()` removes spaces from both the left and right side of strings, and also converts multiple space (or space-like characters) to a single space within strings. (@stephlocke #197) ## Bug fixes and minor improvements diff --git a/R/trim.R b/R/trim.R index 0f7f5a32..3c3ed5cf 100644 --- a/R/trim.R +++ b/R/trim.R @@ -17,3 +17,14 @@ str_trim <- function(string, side = c("both", "left", "right")) { both = stri_trim_both(string) ) } + +#' Trim whitespace from start, middle, and end of string. +#' +#' @export +#' @rdname str_trim +#' @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_trim.Rd b/man/str_trim.Rd index fc3a2eef..aea122f1 100644 --- a/man/str_trim.Rd +++ b/man/str_trim.Rd @@ -2,9 +2,12 @@ % Please edit documentation in R/trim.R \name{str_trim} \alias{str_trim} +\alias{str_squish} \title{Trim whitespace from start and end of string.} \usage{ str_trim(string, side = c("both", "left", "right")) + +str_squish(string) } \arguments{ \item{string}{A character vector.} @@ -16,10 +19,14 @@ A character vector. } \description{ Trim whitespace from start and end of string. + +Trim whitespace from start, middle, and end of string. } \examples{ str_trim(" String with trailing and leading white space\\t") str_trim("\\n\\nString with trailing and leading white space\\n\\n") +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_pad]{str_pad()}} to add whitespace diff --git a/tests/testthat/test-trim.r b/tests/testthat/test-trim.r index 3a50d47e..0dc82ad1 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("str_squish removes excess spaces from all parts of string", { + 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") +})