String

public extension String

This String extension provides utility functions to convert strings to their HTML escaped equivalents and vice versa.

  • Global HTML escape options

    See more

    Declaration

    Swift

    struct HTMLEscapeOptions
  • Return string as HTML escaped by replacing non-ASCII and unsafe characters with their numeric character escapes, or if such exists, their HTML named character reference equivalents. For example, this function turns

    "<script>alert("abc")</script>"

    into

    "&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;"

    You can view/change default option values globally via String.HTMLEscapeOptions.

    Declaration

    Swift

    func htmlEscape(allowUnsafeSymbols: Bool = HTMLEscapeOptions.allowUnsafeSymbols,
                           decimal: Bool = HTMLEscapeOptions.decimal,
                           encodeEverything: Bool = HTMLEscapeOptions.encodeEverything,
                           useNamedReferences: Bool = HTMLEscapeOptions.useNamedReferences)
        -> String

    Parameters

    allowUnsafeSymbols

    Specifies if all ASCII characters should be skipped when escaping text. Optional

    decimal

    Specifies if decimal escapes should be used instead of hexadecimal escapes. Optional

    encodeEverything

    Specifies if all characters should be escaped, even if some are safe characters. Optional

    useNamedReferences

    Specifies if named character references should be used whenever possible. Optional

  • Return string as HTML unescaped by replacing HTML character references with their unicode character equivalents. For example, this function turns

    "&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;"

    into

    "<script>alert(\"abc\")</script>"

    Throws

    (Only if strict == true) The first ParseError encountered during parsing.

    Declaration

    Swift

    func htmlUnescape(strict: Bool) throws -> String

    Parameters

    strict

    Specifies if escapes MUST always end with ;.

  • Return string as HTML unescaped by replacing HTML character references with their unicode character equivalents. For example, this function turns

    "&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;"

    into

    "<script>alert(\"abc\")</script>"

    Equivalent to htmlUnescape(strict: false), but does NOT throw parse error.

    Declaration

    Swift

    func htmlUnescape() -> String