Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Excess whitespace removal throughout a string #197

Merged
merged 3 commits into from
Nov 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions R/trim.R
Original file line number Diff line number Diff line change
Expand Up @@ -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+"," "))
}
7 changes: 7 additions & 0 deletions man/str_trim.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions tests/testthat/test-trim.r
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})