JS处理HTML转义字符

1,063 阅读1分钟

因为小程序无法通过生成dom来处理转义,故这里主要是两块内容。

  • html转义
function htmlDecode(text) {
  let temp = document.createElement("div")
  temp.innerHTML = text
  const output = temp.innerText || temp.textContent
  temp = null
  return output
},
  • 正则匹配 在这里用变量来代替replace//g形式,通过new RegExp()和模板字符串。
const ESCAPE_CHARACTERS = {
  'nbsp': ' ',
  'lt': '<',
  'gt': '>',
  'amp': '&',
  'apos': '\"',
  'ensp': '	 ',
  'emsp': ' ',
  'quot': '"',
  'middot': '·',
  'brvbar': '¦',
  'mdash': '—',
  'ndash': '–',
  'ge': '≥',
  'le': '≤',
  'laquo': '«',
  'raquo': '»',
  'deg': '°',
  'bull': '•',
  'macr': '¯',
  '#64': '@',
  'ldquo': '“',
  'rdquo': '”',
  'rsquo': '‚',
  'lsquo': '‘',
}
// 处理转义字符
handleEscapeChar(str) {
  return str.replace(new RegExp(`&(${ Object.keys(ESCAPE_CHARACTERS).join('|') });`, 'g'), (all, t) => {
    return ESCAPE_CHARACTERS[t]
  })
}