File: trim.R

package info (click to toggle)
r-cran-stringr 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,112 kB
  • sloc: javascript: 11; sh: 9; makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#' Remove whitespace
#'
#' `str_trim()` removes whitespace from start and end of string; `str_squish()`
#' removes whitespace at the start and end, and replaces all internal whitespace
#' with a single space.
#'
#' @inheritParams str_detect
#' @param side Side on which to remove whitespace: "left", "right", or
#'   "both", the default.
#' @return A character vector the same length as `string`.
#' @export
#' @seealso [str_pad()] to add whitespace
#' @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")
str_trim <- function(string, side = c("both", "left", "right")) {
  side <- arg_match(side)

  out <- switch(
    side,
    left = stri_trim_left(string),
    right = stri_trim_right(string),
    both = stri_trim_both(string)
  )
  copy_names(string, out)
}

#' @export
#' @rdname str_trim
str_squish <- function(string) {
  copy_names(string, stri_trim_both(str_replace_all(string, "\\s+", " ")))
}