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

问题描述 投票:0回答:6

是否有使用 JavaScript 或 ES6 编码或解码 HTML 实体的本机方法?例如,

<
将被编码为
&lt;
。 Node.js 有像
html-entities
这样的库,但感觉 JavaScript 中应该内置一些东西来满足这种常见需求。

javascript node.js html-entities
6个回答
30
投票

使用 es6 转义 html 的好函数:

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

7
投票

自己动手(警告 - 在大多数用例中使用 HE 代替)

对于没有库的纯 JS,您可以使用纯 Javascript 编码和解码 HTML 实体,如下所示:

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 库(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'

相关问题


6
投票

JavaScript API 中没有将 ASCII 字符转换为其等效的“html-entities”的本机函数。 这是一个解决方案的开始和一个您可能喜欢的简单技巧


4
投票
对于

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;
 字符。


2
投票
@rasafel 提供的答案(编码)的反向(解码):

const decodeEscapedHTML = (str) => str.replace( /&(\D+);/gi, (tag) => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&#39;': "'", '&quot;': '"', }[tag]), )
    

0
投票
简单的 htmlEncode 和 htmlDecode

HTML 编码功能

function encodeHtml(str) { let buf = []; for (var i = str.length - 1; i >= 0; i--) { if (!(/^[a-zA-Z0-9]$/.test(str[i]))) buf.unshift(['&#', str[i].charCodeAt(), ';'].join('')); else buf.unshift(str[i]) } return buf.join(''); }
HTML解码功能

function decodeHtml(str) { return str.replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec); }); }
    
© www.soinside.com 2019 - 2024. All rights reserved.