Add escape/unescape string

This commit is contained in:
Angelos Chalaris
2017-12-29 14:16:40 +02:00
parent 1f15f00565
commit 1afa5b657d
3 changed files with 34 additions and 4 deletions

14
snippets/escapeString.md Normal file
View File

@ -0,0 +1,14 @@
### escapeString
Escapes a string for use in HTML.
Use a chain of `String.replace()` calls combined with regular expressions to replace special characters with the proper symbols.
```js
const escapeString = str =>
str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
```
```js
escapeString('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
```

View File

@ -0,0 +1,14 @@
### unescapeString
Unescapes a string from HTML.
Use a chain of `String.replace()` calls combined with regular expressions to replace special characters with the proper symbols.
```js
const unescapeString = str =>
str.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&#39;/g, '\'').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
```
```js
unescapeString('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
```