原生JavaScript或ES6方式编码和解码HTML实体?

时间:2016-10-26 13:37:17

标签: javascript node.js html-entities

是否存在使用JavaScript或ES6编码或解码HTML entities的本机方式?例如,<将被编码为&lt;。 Node.js有像html-entities这样的库,但感觉应该有一些内置于JavaScript中的东西已经处理了这个常见的需求。

4 个答案:

答案 0 :(得分:3)

JavaScript API中没有将ASCII字符转换为其“html-entities”等效字符的本机函数。 这是您可能想要的beginning of a solutioneasy trick

答案 1 :(得分:1)

使用es6来转义html的不错功能:

const escapeHTML = str => str.replace(/[&<>'"]/g, 
  tag => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;'
    }[tag] || tag));

答案 2 :(得分:0)

滚动自己的(caveat-在大多数情况下,使用HE代替)

对于不带库的纯JS,您可以这样Encode and Decode HTML entities using pure Javascript

let encode = str => {
  let buf = [];

  for (var i = str.length - 1; i >= 0; i--) {
    buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
  }

  return buf.join('');
}

let decode = str => {
  return str.replace(/&#(\d+);/g, function(match, dec) {
    return String.fromCharCode(dec);
  });
}

用法

encode("Hello > © <") // "&#72;&#101;&#108;&#108;&#111;&#32;&#62;&#32;&#169;&#32;&#60;"
decode("Hello &gt; &copy; &#169; &lt;") // "Hello &gt; &copy; © &lt;"

但是,您可以看到这种方法有一些缺点:


使用HE Library(HTML实体)

用法

he.encode('foo © bar ≠ baz ? qux'); 
// Output : 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'

he.decode('foo &copy; bar &ne; baz &#x1D306; qux');
// Output : 'foo © bar ≠ baz ? qux'

相关问题

答案 3 :(得分:0)

对于unescape HTML实体,您的浏览器很聪明,将为您做到

方法1

_unescape(html: string) :string { 
   const divElement = document.createElement("div");
   divElement.innerHTML = html;
   return divElement.textContent || tmp.innerText || "";
}

方法2

_unescape(html: string) :string {
     let returnText = html;
     returnText = returnText.replace(/&nbsp;/gi, " ");
     returnText = returnText.replace(/&amp;/gi, "&");
     returnText = returnText.replace(/&quot;/gi, `"`);
     returnText = returnText.replace(/&lt;/gi, "<");
     returnText = returnText.replace(/&gt;/gi, ">");
     return returnText;
}

您还可以使用underscorelodash的unescape方法,但这会忽略&nbsp;并仅处理&amp;&lt;&gt;&quot;&#39;个字符。