HTML Encoder/Decoder for Swift

Free online html encoder/decoder with Swift code examples

Working with html encoder/decoder in Swift? Our free online html encoder/decoder helps Swift developers format, validate, and process data instantly. Below you will find Swift code examples using Foundation (built-in) so you can achieve the same result programmatically in your own projects.

Try the HTML Encoder/Decoder Online

Use our free HTML Encoder/Decoder directly in your browser — no setup required.

Open HTML Encoder/Decoder

Swift Code Example

import Foundation

let raw = "<script>alert(\"XSS\")</script>"

// Simple HTML encoding
let encoded = raw
    .replacingOccurrences(of: "&", with: "&amp;")
    .replacingOccurrences(of: "<", with: "&lt;")
    .replacingOccurrences(of: ">", with: "&gt;")
    .replacingOccurrences(of: "\"", with: "&quot;")
    .replacingOccurrences(of: "'", with: "&#39;")

print(encoded)

// Decode using NSAttributedString
if let data = encoded.data(using: .utf8),
   let decoded = try? NSAttributedString(
       data: data,
       options: [.documentType: NSAttributedString.DocumentType.html,
                 .characterEncoding: String.Encoding.utf8.rawValue],
       documentAttributes: nil) {
    print(decoded.string)
}

Quick Setup

Library: Foundation (built-in)
// Built-in framework — no installation needed

Swift Tips & Best Practices

  • Swift has no built-in HTML escape function
  • NSAttributedString can decode HTML entities
  • For server-side Swift, consider swift-html-entities package

Frequently Asked Questions

HTML Encoder/Decoder in Other Languages

More Swift Tools