Skip to content

Instantly share code, notes, and snippets.

@michaeljones
Created July 25, 2019 14:11
Show Gist options
  • Save michaeljones/f80032a28ca894511f3cc32083e4b8a7 to your computer and use it in GitHub Desktop.
Save michaeljones/f80032a28ca894511f3cc32083e4b8a7 to your computer and use it in GitHub Desktop.
Elm port of Lodash Html Escape & Unescape
{- Escaping & unescaping some html in strings
We port over the lodash approach to escaping & unescaping. This does a more minimal approach suitable for large
blocks of html rather than for, say, strings that you're going to put into an html attribute or something. For
reasoning and more aggressive escaping see:
- https://wonko.com/post/html-escaping/
- https://package.elm-lang.org/packages/marcosh/elm-html-to-unicode/latest/
These have been introduced as the more aggressive escaping ends up escaping spaces as well which feels like than
ideal when it comes to data handling in general.
-}
{-| Escape &, <, >, , ", and ' in strings
-}
escape : String -> String
escape string =
Regex.replace unescapedHtmlRegex (withLookup htmlEscapes) string
{-| Unescape the html codes for &, <, >, , ", and ' in strings
-}
unescape : String -> String
unescape string =
Regex.replace escapedHtmlRegex (withLookup htmlUnescapes) string
unescapedHtmlRegex : Regex
unescapedHtmlRegex =
Regex.fromString "[&<>\"']"
|> Maybe.withDefault Regex.never
escapedHtmlRegex : Regex
escapedHtmlRegex =
Regex.fromString "&(amp|lt|gt|quot|#39);"
|> Maybe.withDefault Regex.never
withLookup : Dict String String -> Regex.Match -> String
withLookup dict match =
Dict.get match.match dict
|> Maybe.withDefault ""
htmlEscapes : Dict String String
htmlEscapes =
Dict.fromList
[ ( "&", "&amp;" )
, ( "<", "&lt;" )
, ( ">", "&gt;" )
, ( "\"", "&quot;" )
, ( "'", "&#39;" )
]
htmlUnescapes : Dict String String
htmlUnescapes =
htmlEscapes
|> Dict.toList
|> List.map Tuple2.swap
|> Dict.fromList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment