Native JavaScript or ES6 way to encode and decode

2020-06-30 04:56发布

Is there a native way to encode or decode HTML entities using JavaScript or ES6? For example, < would be encoded as &lt;. There are libraries like html-entities for Node.js but it feels like there should be something built into JavaScript that already handles this common need.

4条回答
一夜七次
2楼-- · 2020-06-30 05:35

To unescape HTML entities, Your browser is smart and will do it for you

Way1

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

Way2

_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;
}

You can also use underscore or lodash's unescape method but this ignores &nbsp; and handles only &amp;, &lt;, &gt;, &quot;, and &#39; characters.

查看更多
Evening l夕情丶
3楼-- · 2020-06-30 05:45

There is no native function in the JavaScript API that convert ASCII characters to their "html-entities" equivalent. Here is a beginning of a solution and an easy trick that you may like

查看更多
Anthone
4楼-- · 2020-06-30 05:46

Roll Your Own (caveat - use HE instead for most use cases)

For pure JS without a lib, you can Encode and Decode HTML entities using pure Javascript like this:

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);
  });
}

Usages:

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

However, you can see this approach has a couple shortcomings:


Use the HE Library (Html Entities)

Usage:

he.encode('foo © bar ≠ baz                                                                     
查看更多
Evening l夕情丶
5楼-- · 2020-06-30 05:56

A nice function using es6 for escaping html:

const escapeHTML = str => str.replace(/[&<>'"]/g, 
  tag => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;'
    }[tag]));
查看更多
登录 后发表回答