Swift — How to check given string is in HTML or not

ODENZA
Sep 7, 2022

In this article, I will show you how to check given string is in html or not in swift.

func isHTMLValidated(_ value: String) -> Bool {
let range = value.range(of: "<(\"[^\"]*\"|'[^']*'|[^'\">])*>", options: .regularExpression)
return range != nil
}

or create a string extension.

extension String {
public var isHTML: Bool {
let range = self.range(of: "<(\"[^\"]*\"|'[^']*'|[^'\">])*>", options: .regularExpression)
return range != nil
}
}

if you just want to check hyperlink (tag <a>)

extension String {
public var isHyperlink: Bool {
let range = self.range(of: "<a([^>]+)>(.+?)</a>", options: .regularExpression)
return range != nil
}
}

Let’s test it.

let text = "<p>This is html string</p>"
let hyperlinkText = "<p>Please visit <a href=\"https://www.google.com\">Click here</a></p>"

Test result:

print("\(isHTMLValidated(testString))") // true
print(text.isHTML) // true
print(hyperlinkText.isHTML) // false
print(hyperlinkText.isHyperlink) // true

--

--