> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/prim/str/method/escapehtml.md).

# str.escapeHTML()

[🔰 JS](/web/js.md) ⟩ [Types](/web/js/val/type.md) ⟩ [String](/web/js/val/prim/str.md) ⟩ [methods](/web/js/val/prim/str/method.md)

{% hint style="success" %}
👉 see: [encodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) ⭐️
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
💾 程式：codepen ⟩ [escapeHTML()](https://codepen.io/lochiwei/pen/VwzLpym?editors=0011) ⭐️

```javascript
// ⭐️ escapeHTML()
export function escapeHTML(str){
    return new Option(str).innerHTML;
}

// ⭐️ str.escapeHTML()
String.prototype.escapeHTML = function(){
    return escapeHTML(this);
}

// ⭐️ escape HTML special characters (deprecated❗️)
String.prototype.escapeHTML = function () {
    return this 
        .replace(/&/g, '&amp;' )    // ampersand (must be first❗️)
        .replace(/>/g, '&gt;'  )    // greater than
        .replace(/</g, '&lt;'  )    // less than
        .replace(/"/g, '&quot;')    // double-quote
        .replace(/'/g, '&#39;' )    // single-quote
        .replace(/`/g, '&#96;' );   // backtick
}
```

{% endtab %}

{% tab title="👥 相關" %}

* [str.replace()](/web/js/val/prim/str/method/str.replace.md)
* [str.kebabToCamelCase()](/web/js/val/prim/str/method/.kebabtocamelcase.md)
* [Events that Cross Shadow DOM Boundary](/web/component/shadow-dom/events/composed.md#custom-events)
* [⭐️ Fav](/web/master/fav.md#code)
  {% endtab %}

{% tab title="📘 手冊" %}

* [encodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) ⭐️
  {% endtab %}

{% tab title="📗 參考" %}

* [x] NEWBEDEV ⟩ [How to escape HTML](https://newbedev.com/how-to-escape-html)
* [ ] GitHub Gist ⟩ [escaping with the DOM](https://gist.github.com/samgreen/8428912)
  {% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="info" %}
Document ⟩ .[createTextNode](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode)() - creates a new [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) node. This method can be used to **escape HTML characters**.
{% endhint %}
{% endtab %}
{% endtabs %}
