Update unescapeString.md

This commit is contained in:
atomiks
2017-12-30 00:08:16 +11:00
committed by GitHub
parent 0914af9814
commit edc4376366

View File

@ -1,14 +1,17 @@
### unescapeString
### unescapeHTML
Unescapes a string from HTML.
Unescapes escaped HTML characters.
Use a chain of `String.replace()` calls combined with regular expressions to replace special characters with the proper symbols.
Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
```js
const unescapeString = str =>
str.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&#39;/g, '\'').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
```
const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&#39;': '\'',
'&quot;': '"'
})[tag] || tag);```
```js
unescapeString('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
```