转义字符串中的'&', '<', '>', '"', "'", "`" 字符为HTML实体字符

/**
 * 转义字符串中的'&', '<', '>', '"', "'", "`" 字符为HTML实体字符
 * **注意:** 不会转义其他字符
 * Converts the characters '&', '<', '>', '"', "'", "`" in `string` to their corresponding HTML entities.
 * **Note:** No other characters are escaped.
 * @param {string} [string=''] The string to escape
 * @returns {string} Returns the escaped string
 * @example
 * escape('fred, barney, & pebbles')
 * // => 'fred, barney, &amp; pebbles'
 */

import toString from "./toString"

// Used to match HTML characters
var reUnescapedHtml = /[&<>"']/g
var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source)

// Used to map characters to HTML entities.
var htmlEscapes = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
}

function basePropertyOf(object) {
  return function(key) {
    return object == null ? undefined : object[key]
  }
}

var escapeHtmlChar = basePropertyOf(htmlEscapes)

function escape(string) {
  string = toString(string)
  return string && reHasUnescapedHtml.test(string)
    ? string.replace(reUnescapedHtml, escapeHtmlChar)
    : string
}

export default escape
/**
 * Converts `value` to a string. An empty string is returned for `null` and `undefined` values.
 * The sign of `-0` is preserved.
 * 转换`value`成字符串,`null`和`undefined`返回空字符串,`-0`转成'-0'
 * @param {*} value The value to convert
 * @retuens {string} Returns the converted string
 * @example
 * toString(null)
 * // => ''
 * toString(-0)
 * // => '-0'
 * toString([1, 2, 3])
 * // => '1, 2, 3'
 * toString({a: 1})
 * // => [object Object]
 */

const symbolTag = "[object Symbol]"

function isObjectLike(value) {
  return typeof value == "object" && value !== null;
}

function isSymbol(value) {
  return (
    typeof value === "symbol" ||
    (isObjectLike(value) && Object.prototype.toString.call(value) === symbolTag)
  )
}

function arrayMap(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length,
    result = Array(length)

  while (++index < length) {
    result[index] = iteratee(array[index], index, array)
  }
  return result
}

function baseToString(value) {
  if (typeof value === "string") {
    return value
  }
  if (Array.isArray(value)) {
    return arrayMap(value, baseToString) + ""
  }
  if (isSymbol(value)) {
    return Symbol.prototype.toString
      ? Symbol.prototype.toString.call(value)
      : ""
  }
  var result = value + ""
  return result == "0" && 1 / value == -Infinity ? "-0" : result
}

function toString(value) {
  return value == null ? "" : baseToString(value)
}

export default toString

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值