Skip to content

Commit 17515f2

Browse files
stephlockehadley
authored andcommitted
Excess whitespace removal throughout a string (#197)
1 parent deac571 commit 17515f2

File tree

5 files changed

+27
-0
lines changed

5 files changed

+27
-0
lines changed

NAMESPACE

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export(str_replace_na)
3333
export(str_sort)
3434
export(str_split)
3535
export(str_split_fixed)
36+
export(str_squish)
3637
export(str_sub)
3738
export(str_subset)
3839
export(str_to_lower)

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
* `str_remove()` and `str_remove_all()` functions. These wrap
1313
`str_replace()` and `str_replace_all()` to remove patterns from strings.
1414
(@Shians, #178)
15+
16+
* `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)
1517

1618
## Bug fixes and minor improvements
1719

R/trim.R

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,14 @@ str_trim <- function(string, side = c("both", "left", "right")) {
1717
both = stri_trim_both(string)
1818
)
1919
}
20+
21+
#' Trim whitespace from start, middle, and end of string.
22+
#'
23+
#' @export
24+
#' @rdname str_trim
25+
#' @examples
26+
#' str_squish(" String with trailing, middle, and leading white space\t")
27+
#' str_squish("\n\nString with excess, trailing and leading white space\n\n")
28+
str_squish <- function(string) {
29+
stri_trim_both(str_replace_all(string,"\\s+"," "))
30+
}

man/str_trim.Rd

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-trim.r

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,9 @@ test_that("side argument restricts trimming", {
1616
expect_equal(str_trim(" abc ", "left"), "abc ")
1717
expect_equal(str_trim(" abc ", "right"), " abc")
1818
})
19+
20+
test_that("str_squish removes excess spaces from all parts of string", {
21+
expect_equal(str_squish("ab\t\tc\t"), "ab c")
22+
expect_equal(str_squish("\ta bc"), "a bc")
23+
expect_equal(str_squish("\ta\t bc\t"), "a bc")
24+
})

0 commit comments

Comments
 (0)