簡體   English   中英

原生 JavaScript 或 ES6 編碼和解碼 HTML 實體的方式?

[英]Native JavaScript or ES6 way to encode and decode HTML entities?

是否有使用 JavaScript 或 ES6 編碼或解碼HTML 實體的本機方法? 例如, <將被編碼為&lt; . 有像 Node.js 的html-entities這樣的庫,但感覺應該在 JavaScript 中內置一些東西來處理這個常見的需求。

使用 es6 轉義 html 的一個不錯的函數:

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

JavaScript API 中沒有將 ASCII 字符轉換為它們的“html-entities”等價物的本機函數。 這是您可能喜歡的解決方案簡單技巧開始

自己動手(警告 - 在大多數用例中使用 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'

相關問題

要取消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;
}

您也可以使用下划線lodash的 unescape 方法,但這會忽略&nbsp; 並且只處理&amp; &lt; , &gt; , &quot; , 和&#39; 字符。

@rasafel 提供的答案(編碼)的反向(解碼):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM