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>'
```

View File

@ -1,6 +1,6 @@
anagrams:string anagrams:string
arrayToHtmlList:browser arrayToHtmlList:browser
average:uncategorized average:math
bottomVisible:browser bottomVisible:browser
call:adapter call:adapter
capitalize:string capitalize:string
@ -30,6 +30,7 @@ dropElements:array
dropRight:array dropRight:array
elementIsVisibleInViewport:browser elementIsVisibleInViewport:browser
escapeRegExp:string escapeRegExp:string
escapeString:string
everyNth:array everyNth:array
extendHex:utility extendHex:utility
factorial:math factorial:math
@ -76,9 +77,9 @@ JSONToFile:node
last:array last:array
lcm:math lcm:math
mapObject:array mapObject:array
max:uncategorized max:math
median:math median:math
min:uncategorized min:math
negate:logic negate:logic
nthElement:array nthElement:array
objectFromPairs:object objectFromPairs:object
@ -120,7 +121,7 @@ sortCharactersInString:string
speechSynthesis:media speechSynthesis:media
spreadOver:adapter spreadOver:adapter
standardDeviation:math standardDeviation:math
sum:uncategorized sum:math
symmetricDifference:array symmetricDifference:array
tail:array tail:array
take:array take:array
@ -136,6 +137,7 @@ toOrdinalSuffix:utility
toSnakeCase:string toSnakeCase:string
truncateString:string truncateString:string
truthCheckCollection:object truthCheckCollection:object
unescapeString:string
union:array union:array
UUIDGeneratorBrowser:browser UUIDGeneratorBrowser:browser
UUIDGeneratorNode:node UUIDGeneratorNode:node