Files
30-seconds-of-code/snippets/unescapeHTML.md
2022-05-14 15:55:07 +03:00

34 lines
825 B
Markdown

---
title: Unescape HTML
tags: string,browser,regexp
expertise: beginner
cover: blog_images/little-tree.jpg
firstSeen: 2017-12-29T15:09:10+02:00
lastUpdated: 2020-10-22T20:24:44+03:00
---
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).
```js
const unescapeHTML = str =>
str.replace(
/&|<|>|'|"/g,
tag =>
({
'&': '&',
'&lt;': '<',
'&gt;': '>',
'&#39;': "'",
'&quot;': '"'
}[tag] || tag)
);
```
```js
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;');
// '<a href="#">Me & you</a>'
```