• Stars
    star
    170
  • Rank 223,322 (Top 5 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTML5 spec-compliant character encoder/decoder for Swift

HTMLEntities

Build Status - Master macOS Linux Apache 2 codecov Carthage compatible

Summary

Pure Swift HTML encode/decode utility tool for Swift.

Includes support for HTML5 named character references. You can find the list of all 2231 HTML5 named character references here.

HTMLEntities can escape ALL non-ASCII characters as well as the characters <, >, &, ", โ€™, as these five characters are part of the HTML tag and HTML attribute syntaxes.

In addition, HTMLEntities can unescape encoded HTML text that contains decimal, hexadecimal, or HTML5 named character references.

API Documentation

API documentation for HTMLEntities is located here.

Features

  • Supports HTML5 named character references (NegativeMediumSpace; etc.)
  • HTML5 spec-compliant; strict parse mode recognizes parse errors
  • Supports decimal and hexadecimal escapes for all characters
  • Simple to use as functions are added by way of extending the default String class
  • Minimal dependencies; implementation is completely self-contained

Version Info

Latest release of HTMLEntities requires Swift 4.0 and higher.

Installation

Via Swift Package Manager

Add HTMLEntities to your Package.swift:

import PackageDescription

let package = Package(
  name: "<package-name>",
  ...
  dependencies: [
    .package(url: "https://github.com/Kitura/swift-html-entities.git", from: "3.0.0")
  ]
  // Also, make sure to add HTMLEntities to your package target's dependencies
)

Via CocoaPods

Add HTMLEntities to your Podfile:

target '<project-name>' do
  pod 'HTMLEntities', :git => 'https://github.com/Kitura/swift-html-entities.git'
end

Via Carthage

Add HTMLEntities to your Cartfile:

github "Kitura/swift-html-entities"

Usage

import HTMLEntities

// encode example
let html = "<script>alert(\"abc\")</script>"

print(html.htmlEscape())
// Prints "&#x3C;script&#x3E;alert(&#x22;abc&#x22;)&#x3C;/script&#x3E;"

// decode example
let htmlencoded = "&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;"

print(htmlencoded.htmlUnescape())
// Prints "<script>alert(\"abc\")</script>"

Advanced Options

HTMLEntities supports various options when escaping and unescaping HTML characters.

Escape Options

allowUnsafeSymbols

Defaults to false. Specifies if unsafe ASCII characters should be skipped or not.

import HTMLEntities

let html = "<p>\"cafรฉ\"</p>"

print(html.htmlEscape())
// Prints "&#x3C;p&#x3E;&#x22;caf&#xE9;&#x22;&#x3C;/p&#x3E;"

print(html.htmlEscape(allowUnsafeSymbols: true))
// Prints "<p>\"caf&#xE9;\"</p>"

decimal

Defaults to false. Specifies if decimal character escapes should be used instead of hexadecimal character escapes whenever numeric character escape is used (i.e., does not affect named character references escapes). The use of hexadecimal character escapes is recommended.

import HTMLEntities

let text = "แ„’แ…กแ†ซ, ํ•œ, แบฟ, eฬ‚ฬ, ๐Ÿ‡บ๐Ÿ‡ธ"

print(text.htmlEscape())
// Prints "&#x1112;&#x1161;&#x11AB;, &#xD55C;, &#x1EBF;, e&#x302;&#x301;, &#x1F1FA;&#x1F1F8;"

print(text.htmlEscape(decimal: true))
// Prints "&#4370;&#4449;&#4523;, &#54620;, &#7871;, e&#770;&#769;, &#127482;&#127480;"

encodeEverything

Defaults to false. Specifies if all characters should be escaped, even if some characters are safe. If true, overrides the setting for allowUnsafeSymbols.

import HTMLEntities

let text = "A quick brown fox jumps over the lazy dog"

print(text.htmlEscape())
// Prints "A quick brown fox jumps over the lazy dog"

print(text.htmlEscape(encodeEverything: true))
// Prints "&#x41;&#x20;&#x71;&#x75;&#x69;&#x63;&#x6B;&#x20;&#x62;&#x72;&#x6F;&#x77;&#x6E;&#x20;&#x66;&#x6F;&#x78;&#x20;&#x6A;&#x75;&#x6D;&#x70;&#x73;&#x20;&#x6F;&#x76;&#x65;&#x72;&#x20;&#x74;&#x68;&#x65;&#x20;&#x6C;&#x61;&#x7A;&#x79;&#x20;&#x64;&#x6F;&#x67;"

// `encodeEverything` overrides `allowUnsafeSymbols`
print(text.htmlEscape(allowUnsafeSymbols: true, encodeEverything: true))
// Prints "&#x41;&#x20;&#x71;&#x75;&#x69;&#x63;&#x6B;&#x20;&#x62;&#x72;&#x6F;&#x77;&#x6E;&#x20;&#x66;&#x6F;&#x78;&#x20;&#x6A;&#x75;&#x6D;&#x70;&#x73;&#x20;&#x6F;&#x76;&#x65;&#x72;&#x20;&#x74;&#x68;&#x65;&#x20;&#x6C;&#x61;&#x7A;&#x79;&#x20;&#x64;&#x6F;&#x67;"

useNamedReferences

Defaults to false. Specifies if named character references should be used whenever possible. Set to false to always use numeric character references, i.e., for compatibility with older browsers that do not recognize named character references.

import HTMLEntities

let html = "<script>alert(\"abc\")</script>"

print(html.htmlEscape())
// Prints โ€œ&#x3C;script&#x3E;alert(&#x22;abc&#x22;)&#x3C;/script&#x3E;โ€

print(html.htmlEscape(useNamedReferences: true))
// Prints โ€œ&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;โ€

Set Escape Options Globally

HTML escape options can be set globally so that you don't have to set them everytime you want to escape a string. The options are managed in the String.HTMLEscapeOptions struct.

import HTMLEntities

// set `useNamedReferences` to `true` globally
String.HTMLEscapeOptions.useNamedReferences = true

let html = "<script>alert(\"abc\")</script>"

// Now, the default behavior of `htmlEscape()` is to use named character references
print(html.htmlEscape())
// Prints โ€œ&lt;script&gt;alert(&quot;abc&quot;)&lt;/script&gt;โ€

// And you can still go back to using numeric character references only
print(html.htmlEscape(useNamedReferences: false))
// Prints "&#x3C;script&#x3E;alert(&#x22;abc&#x22;)&#x3C;/script&#x3E;"

Unescape Options

strict

Defaults to false. Specifies if HTML5 parse errors should be thrown or simply passed over.

Note: htmlUnescape() is a throwing function if strict is used in call argument (no matter if it is set to true or false); htmlUnescape() is NOT a throwing function if no argument is provided.

import HTMLEntities

let text = "&#4370&#4449&#4523"

print(text.htmlUnescape())
// Prints "ํ•œ"

print(try text.htmlUnescape(strict: true))
// Throws a `ParseError.MissingSemicolon` instance

// a throwing function because `strict` is passed in argument
// but no error is thrown because `strict: false`
print(try text.htmlUnescape(strict: false))
// Prints "ํ•œ"

Acknowledgments

HTMLEntities was designed to support some of the same options as he, a popular Javascript HTML encoder/decoder.

License

Apache 2.0

More Repositories

1

Kitura

A Swift web framework and HTTP server.
Swift
7,628
star
2

BlueSocket

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.
Swift
1,407
star
3

Swift-JWT

JSON Web Tokens in Swift
Swift
559
star
4

Swift-Kuery

SQL database abstraction layer
Swift
426
star
5

Swift-SMTP

Swift SMTP client
Swift
261
star
6

Swift-Kuery-ORM

An ORM for Swift, built on Codable
Swift
212
star
7

BlueCryptor

Swift cross-platform crypto library using CommonCrypto/libcrypto
Swift
191
star
8

HeliumLogger

A lightweight logging framework for Swift
Swift
176
star
9

swift-ubuntu-docker

๐Ÿšซ This repo is deprecated - please use the images here: https://hub.docker.com/_/swift
Vim Script
154
star
10

BlueRSA

RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
Swift
132
star
11

SwiftyRequest

SwiftyRequest is an HTTP networking library built for Swift.
Swift
110
star
12

Kitura-net

Kitura networking
Swift
104
star
13

BlueSSLService

SSL/TLS Add-in for BlueSocket using Secure Transport and OpenSSL
Swift
97
star
14

Kitura-redis

Swift Redis library
Swift
95
star
15

BlueECC

Elliptic-curve cryptography for Swift
Swift
94
star
16

BlueSignals

Generic Cross Platform Signal Handler
Swift
94
star
17

Configuration

Hierarchical configuration manager for Swift applications
Swift
81
star
18

Kitura-Sample

A sample application that shows how to use various features of Kitura
Swift
81
star
19

Kitura-WebSocket

WebSocket support for Kitura
Swift
68
star
20

OpenSSL

Swift modulemaps for libSSL and libcrypto
C
61
star
21

Swift-Kuery-PostgreSQL

PostgreSQL plugin for Swift-Kuery framework
Swift
61
star
22

SwiftKafka

Swift SDK for Apache Kafka
Swift
60
star
23

KituraKit

Swift client library for using Codable routes with Kitura
Swift
59
star
24

Kitura-CouchDB

CouchDB adapter for Kitura
Swift
51
star
25

CircuitBreaker

A Swift Circuit Breaker library โ€“ Improves application stability and reliability.
Swift
47
star
26

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura
Swift
41
star
27

Kitura-NIO

A networking library for Kitura, based on SwiftNIO
Swift
38
star
28

Kitura-OpenAPI

OpenAPI support for Kitura
Swift
37
star
29

TypeDecoder

A Swift library to allow the runtime inspection of Swift language native and complex types.
Swift
37
star
30

SwiftKueryMySQL

MySQL plugin for Swift-Kuery framework
Swift
35
star
31

Package-Builder

Build and utility scripts used for continuous integration builds for Swift Package Manager projects on the Travis CI environment
Shell
35
star
32

CCurl

Modulemap for the libcurl library
Objective-C
31
star
33

Kitura-StencilTemplateEngine

Stencil templating for Kitura
Swift
27
star
34

Kitura-Markdown

Templating engine for Kitura that uses Markdown based templates
C
26
star
35

LoggerAPI

Logger protocol
Swift
26
star
36

kitura.dev

http://www.kitura.dev
JavaScript
26
star
37

Health

An application health library for Swift.
Swift
22
star
38

Kitura-Session

A pluggable framework for managing user sessions in a Swift server using Kitura
Swift
19
star
39

Kitura-WebSocket-NIO

A SwiftNIO based implementation of WebSocket for Kitura
Swift
18
star
40

CommonCrypto

CommonCrypto Module Map
Swift
18
star
41

FileKit

Swift
17
star
42

Kitura-TemplateEngine

Kitura Template Engine protocol
Swift
16
star
43

Swift-Kuery-SQLite

An SQLite plugin for the Swift-Kuery framework
Swift
16
star
44

Kitura-CredentialsHTTP

A plugin for the Kitura-Credentials framework that authenticates using HTTP Basic and Digest authentication
Swift
16
star
45

kitura-cli

โŒจ๏ธ Kitura command-line interface
Go
14
star
46

KituraContracts

A library containing type definitions shared by client and server Kitura code.
Swift
13
star
47

CZlib

Module map for Zlib library
Swift
12
star
48

CloudEnvironment

Convenience Swift package for accessing environment variables, credentials.
Swift
12
star
49

Kitura-CredentialsFacebook

A plugin for the Kitura-Credentials framework that authenticates using the Facebook web login
Swift
10
star
50

Kitura-CORS

Kitura CORS middleware
Swift
10
star
51

Kitura-Cache

Kitura cache
Swift
10
star
52

Kitura-CredentialsGoogle

A plugin for the Kitura-Credentials framework that authenticates using the Google web login
Swift
9
star
53

Swift-cfenv

Easy access to Cloud Foundry application environment for Swift Packages.
Swift
9
star
54

Kitura-Compression

Kitura compression middleware
Swift
7
star
55

CEpoll

A modulemap file and include to help Swift code use epoll on Linux
Swift
6
star
56

Kitura-WebSocket-Client

A WebSocket client based on SwiftNIO
Swift
6
star
57

Kitura-CredentialsGitHub

A plugin for the Kitura-Credentials framework that authenticates using the GitHub web login
Swift
6
star
58

Kitura-MustacheTemplateEngine

Adapter of GRMustache Template Engine to Kitura Template Engine
Swift
5
star
59

CHTTPParser

Modulemap for the http-parser library
C
5
star
60

Kitura-WebSocket-Compression

A WebSocket compression library based on SwiftNIO
Swift
4
star
61

generator-swiftserver-projects

Autogenerated Kitura projects
Shell
4
star
62

Kitura-Session-Redis

Kitura-Session store using Redis as the backing store
Swift
4
star
63

Kitura-Benchmarks

Benchmarks for Kitura
Swift
3
star
64

homebrew-kitura

Homebrew tap
Ruby
3
star
65

Kitura-CredentialsJWT

A plugin for the Kitura-Credentials framework that supports JWT authentication.
Swift
3
star
66

ShellToolKit

Utility classes to help with common system/shell actions in Swift
Swift
3
star
67

anapistula

Simple standalone web server in swift
Swift
2
star
68

CLibpq

PostgreSQL wrapper
Swift
2
star
69

CMySQL

Swift
1
star
70

Kitura-CI

Repository to hold the testing scripts for some Kitura repositories
Shell
1
star
71

Maintainers

Files relevant to Kitura project maintainers
Swift
1
star
72

StarterWebServer

A starter web server that can be used as a template for a new project
Swift
1
star