30秒学会 JavaScript 片段 · 2022年7月1日

30秒学会 JavaScript 片段 – Unescape HTML

Unescapes escaped HTML characters.

  • Use String.prototype.replace() with a regexp that matches the characters that need to be unescaped.
  • Use the function’s callback to replace each escaped character instance with its associated unescaped character using a dictionary (object).

代码实现

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

unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;');
// '<a href="#">Me & you</a>'

翻译自:https://www.30secondsofcode.org/js/s/unescape-html