30-seconds-of-code
Version:
A collection of useful JavaScript snippets.
25 lines (20 loc) • 637 B
Markdown
Unescapes escaped HTML characters.
Use `String.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
```js
const unescapeHTML = str =>
str.replace(
/&|<|>|&
tag =>
({
'&': '&',
'<': '<',
'>': '>',
''': "'",
'"': '"'
}[tag] || tag)
);
```
```js
unescapeHTML('<a href="#">Me & you</a>'); // '<a href="#">Me & you</a>'
```