Stripping out HTML tags from a string

Led picture Led · Sep 22, 2014 · Viewed 47.6k times · Source

How do I remove HTML tags from a string so that I can output clean text?

let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)

Answer

Steve Rosenberg picture Steve Rosenberg · Sep 23, 2014

Hmm, I tried your function and it worked on a small example:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)

//output "  My First Heading My first paragraph. "

Can you give an example of a problem?

Swift 4 and 5 version:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)