R/htmlspecialchars.R

Defines functions htmlspecialchars

Documented in htmlspecialchars

#' Replace HTML special characters with HTML entities
#'
#' The characters \code{c("&", '"', "'", "<", ">")} will be replaced with
#' \code{c("&amp;", "&quot;", "&#039;", "&lt;", "&gt;")}, respectively.
#' @param string the string with (or w/o) HTML special chars
#' @return the string with special chars replaced.
#' @author Yihui Xie <\url{http://yihui.name}>
#' @seealso \code{\link{gsub}}
#' @references This function is copied directly from
#'   \href{yihui/fun}{https://github.com/yihui/fun/blob/master/R/htmlspecialchars.R}.
#' @export
#' @examples
#' htmlspecialchars("<a href = 'http://yihui.name'>Yihui</a>")
#' # &lt;a href = &#039;http://yihui.name&#039;&gt;Yihui&lt;/a&gt;
htmlspecialchars <- function(string) {
  x = c("&", '"', "'", "<", ">")
  subx = c("&amp;", "&quot;", "&#039;", "&lt;", "&gt;")
  for (i in seq_along(x)) {
    string = gsub(x[i], subx[i], string, fixed = TRUE)
  }
  string
}
liao961120/rmdtk documentation built on May 7, 2019, 8:22 a.m.