Skip to contentSaltar al contenido
125+ QA and SEO checks per page

HTML Sanitizer Implementation in Swift

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓HTML Sanitizer runs in O(n) time and O(n) space, in Swift as in every other language.
  • ✓Foundation supplies XMLParser, an event-driven parser exposing didStartElement, didEndElement and foundCharacters, together with shouldProcessNamespaces and externalEntityResolvingPolicy.
  • ✓XMLParserDelegate is an Objective-C protocol, so the conformer must be a class inheriting NSObject; a struct will not compile, and a free-floating global sink will not pass review.
  • ✓The Swift trap: NSAttributedString(data:options:documentAttributes:) with a documentType of .html is the shortcut everyone reaches for, and it is not a sanitizer.
  • ✓String is copy-on-write with grapheme-cluster semantics, so iterating Characters performs Unicode boundary work that markup escaping does not need; walk unicodeScalars or utf8 and append into a single buffer after reserveCapacity.

What HTML Sanitizer actually is

An HTML sanitizer takes markup from somewhere you do not control and returns markup you are willing to put on a page. Exactly one design survives contact with real input: parse the string with a genuine HTML parser, walk the tree it produces, keep only the elements and attributes named on an allowlist, and serialise what is left. Shortcuts around that fail for structural reasons. Matching tags with a regular expression fails because HTML is not a regular language and browsers recover aggressively from garbage: an unterminated attribute value, a missing closing bracket, a stray second angle bracket all still produce elements. A denylist fails because the set of dangerous names grows with every browser release while the set of harmless ones does not. Three hazards then survive a naive allowlist. URL-bearing attributes carry their own mini-language, so href and src need a scheme decision: javascript: executes on activation, data: can smuggle an entire document, and legacy vbscript: is still on payload lists, while https: and mailto: are inert. Foreign content breaks the assumption that a tag name identifies an element, because inside svg or math the names a, title and style parse under different rules. And mutation XSS appears when a sanitized tree is serialised and parsed again, since the second parse can build a different tree from the first, turning inert output live with nothing added. The eight languages diverge hard here. Two get a spec-compliant parser free from the platform they already run on. One ships a tokenizer with no tree at all, so the open-element stack is yours to carry. Five have no HTML parser in the standard library and route you to one well-known package. One expresses the trust boundary in types and then erases it before anything runs. One will hand your walker a counterfeit attribute list. And in one, deleting a node mid-walk quietly ends the walk.

HTML Sanitizer in Swift: what you actually reach for

Foundation supplies XMLParser, an event-driven parser exposing didStartElement, didEndElement and foundCharacters, together with shouldProcessNamespaces and externalEntityResolvingPolicy. It parses XML, which means well-formed XHTML and nothing more: genuine tag soup fails outright rather than being recovered the way a browser recovers it. URL and URLComponents provide scheme. No HTML5 tree builder exists on Apple platforms outside WebKit, so arbitrary markup goes to SwiftSoup, a pure-Swift port of jsoup, or to a hosted WKWebView.

Swift implementation

XMLParserDelegate is an Objective-C protocol, so the conformer must be a class inheriting NSObject; a struct will not compile, and a free-floating global sink will not pass review. Marking that class final is a good idiom for a leaf delegate with no subclasses, not a language requirement. Set externalEntityResolvingPolicy to .never explicitly rather than trusting a default to stay put. Return String? or throw, never an empty string on failure, since an empty result is otherwise indistinguishable from empty input. Keep the policy itself in let value types, and annotate anything that touches Foundation's HTML importer as @MainActor.
swift
import Foundation

private let policy: [String: Set<String>] = [
    "p": [], "em": [], "code": [], "figcaption": [], "a": ["href", "hreflang"],
]
private let safeSchemes: Set<String> = ["https", "mailto"]
private let xhtmlNS = "http://www.w3.org/1999/xhtml"
/// XMLParserDelegate is an Objective-C protocol: the conformer must be a class
/// inheriting NSObject, so a struct will not compile here.
final class FragmentSanitizer: NSObject, XMLParserDelegate {
    private var out = ""
    private var skip = 0
    static func sanitize(_ fragment: String) -> String? {
        let sink = FragmentSanitizer()
        let parser = XMLParser(data: Data(fragment.utf8))
        parser.delegate = sink
        parser.shouldProcessNamespaces = true
        parser.externalEntityResolvingPolicy = .never  // no DTD or entity fetches
        return parser.parse() ? sink.out : nil
    }

    func parser(_ parser: XMLParser, didStartElement element: String, namespaceURI: String?,
                qualifiedName qName: String?, attributes attrs: [String: String] = [:]) {
        guard skip == 0, namespaceURI == nil || namespaceURI == xhtmlNS,
              let allowed = policy[element] else { skip += 1; return }
        out += "<" + element
        for key in attrs.keys.sorted() where allowed.contains(key) {
            let raw = attrs[key]!.trimmingCharacters(in: .whitespacesAndNewlines)
            if key == "href", let s = URL(string: raw)?.scheme,
               !safeSchemes.contains(s.lowercased()) { continue }
            out += " \(key)=\"\(escaped(raw))\""
        }
        out += ">"
    }
    func parser(_ p: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName q: String?) {
        if skip > 0 { skip -= 1 } else { out += "</\(element)>" }
    }
    func parser(_ p: XMLParser, foundCharacters text: String) {
        if skip == 0 { out += escaped(text) }
    }
    private func escaped(_ s: String) -> String {
        s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
            .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Swift-specific trap

NSAttributedString(data:options:documentAttributes:) with a documentType of .html is the shortcut everyone reaches for, and it is not a sanitizer. It invokes the full WebKit HTML importer, which Apple documents as main-thread only, so calling it from a background queue produces a crash or a hang rather than a slow path. Worse for this purpose, the importer honours the document it is handed: external references in hostile markup turn a paste into outbound requests from the user's device, so the sender learns the reader opened it without a single script running.

Performance in Swift, beyond the O(n)

String is copy-on-write with grapheme-cluster semantics, so iterating Characters performs Unicode boundary work that markup escaping does not need; walk unicodeScalars or utf8 and append into a single buffer after reserveCapacity. Chained replacingOccurrences(of:with:) calls are the readable escape and also the expensive one, four whole-string traversals producing four intermediate strings. On Apple platforms each delegate callback crosses the Objective-C boundary, so its String arguments are bridged from NSString and the resulting ARC traffic shows up as swift_retain and swift_release in a profile of a large document. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port HTML Sanitizer between languages.

Real-World Applications

HTML Sanitizer is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding HTML Sanitizer helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

HTML Sanitizer appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose HTML Sanitizer over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of HTML Sanitizer to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for HTML Sanitizer?

Foundation supplies XMLParser, an event-driven parser exposing didStartElement, didEndElement and foundCharacters, together with shouldProcessNamespaces and externalEntityResolvingPolicy. It parses XML, which means well-formed XHTML and nothing more: genuine tag soup fails outright rather than being recovered the way a browser recovers it. URL and URLComponents provide scheme. No HTML5 tree builder exists on Apple platforms outside WebKit, so arbitrary markup goes to SwiftSoup, a pure-Swift port of jsoup, or to a hosted WKWebView.

What is the most common Swift mistake when implementing HTML Sanitizer?

NSAttributedString(data:options:documentAttributes:) with a documentType of .html is the shortcut everyone reaches for, and it is not a sanitizer. It invokes the full WebKit HTML importer, which Apple documents as main-thread only, so calling it from a background queue produces a crash or a hang rather than a slow path. Worse for this purpose, the importer honours the document it is handed: external references in hostile markup turn a paste into outbound requests from the user's device, so the sender learns the reader opened it without a single script running.

How does HTML Sanitizer actually perform in Swift?

String is copy-on-write with grapheme-cluster semantics, so iterating Characters performs Unicode boundary work that markup escaping does not need; walk unicodeScalars or utf8 and append into a single buffer after reserveCapacity. Chained replacingOccurrences(of:with:) calls are the readable escape and also the expensive one, four whole-string traversals producing four intermediate strings. On Apple platforms each delegate callback crosses the Objective-C boundary, so its String arguments are bridged from NSString and the resulting ARC traffic shows up as swift_retain and swift_release in a profile of a large document. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.