Merge pull request #388 from Chalarangelo/escape-unescape-string

[FEATURE] Add escape/unescape string
This commit is contained in:
Angelos Chalaris
2017-12-29 15:21:25 +02:00
committed by GitHub
3 changed files with 38 additions and 0 deletions

19
snippets/escapeHTML.md Normal file
View File

@ -0,0 +1,19 @@
### escapeHTML
Escapes a string for use in HTML.
Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
```js
const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'\'': '&#39;',
'"': '&quot;'
})[tag] || tag);
```
```js
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
```

17
snippets/unescapeHTML.md Normal file
View File

@ -0,0 +1,17 @@
### unescapeHTML
Unescapes escaped HTML characters.
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 unescapeHTML = str => str.replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, tag => ({
'&amp;': '&',
'&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>'
```